我試圖找出正確的正則運算式,用最后一段的修改版本替換 url 的最后一段。(我知道那里有類似的執行緒,但似乎沒有任何幫助......)
例子:
https://www.test.com/one/two/three/mypost/
--->
one/two/three?id=mypost
https://www.test.com/one/mypost/
--->
one?id=mypost
現在我被困在這里:https : //regex101.com/r/9GqYaU/1
我可以在捕獲組 2 中獲取最后一個片段,但我將如何替換它?我想我將不得不這樣做:
const url = 'https://www.test.com/one/two/three/mypost/'
const regex = /(http[s]?:\/\/)([^\/] \/)*(?=\/$|$)/
const path = url.replace(regex, `${myUrlWithoutTheLastSegmentAnd WithoutHTTPS}?id=$2`)
return path
但我不知道如何在沒有最后一段的情況下獲取 url。我目前只能訪問整個字串或第 1 組(在這種情況下這是無用的),然后是第 2 組,但不能訪問沒有第 2 組的字串。
我會很高興在這里得到任何幫助。有時我只是缺乏正則運算式的可能性以及如何實作它的知識。
先感謝您。
干杯
uj5u.com熱心網友回復:
您可以使用 URL 類來提取路徑名并substring洗掉第一個“/”。
然后,您可以將路徑名的最后一部分放在一個組中,并將其用作$1替換的參考。
const url = new URL('https://www.test.com/one/two/three/mypost/').pathname.substring(1)
console.log(url.replace(/\/([^/]*)\/$/, '?id=$1'))
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/388135.html
標籤:javascript 正则表达式 细绳 代替
