【发布时间】:2022-01-22 11:54:51
【问题描述】:
我试图找出正确的正则表达式,用最后一段的修改版本替换网址的最后一段。 (我知道那里有类似的线程,但似乎没有任何帮助......)
例子:
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 组的字符串。
我会很高兴在这里得到任何帮助。有时我只是不了解正则表达式的可能性以及如何实现它。
提前谢谢你。
干杯
【问题讨论】:
标签: javascript regex string replace