正则表达式:替换 url 的最后一段
Regex: Replace last segment of url
我试图找出正确的正则表达式,用最后一段的修改版本替换 url 的最后一段。 (我知道那里有类似的帖子,但 none 似乎有帮助...)
示例:
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=`)
return path
但我不知道如何在没有最后一段的情况下获得 url。我目前只能访问整个字符串或第 1 组(在这种情况下无用),然后是第 2 组,但不能访问没有第 2 组的字符串。
我很乐意在这里提供任何帮助。有时我只是不了解正则表达式的可能性以及如何实现它。
提前谢谢你。
干杯
您可以使用 URL class 提取路径名并使用 substring
删除第一个“/”。
然后,您可以将路径名的最后一部分放在一个组中,并将其用作替换的参考</code>。</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre><code>const url = new URL('https://www.test.com/one/two/three/mypost/').pathname.substring(1)
console.log(url.replace(/\/([^/]*)\/$/, '?id='))
我试图找出正确的正则表达式,用最后一段的修改版本替换 url 的最后一段。 (我知道那里有类似的帖子,但 none 似乎有帮助...)
示例:
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=`)
return path
但我不知道如何在没有最后一段的情况下获得 url。我目前只能访问整个字符串或第 1 组(在这种情况下无用),然后是第 2 组,但不能访问没有第 2 组的字符串。
我很乐意在这里提供任何帮助。有时我只是不了解正则表达式的可能性以及如何实现它。
提前谢谢你。
干杯
您可以使用 URL class 提取路径名并使用 substring
删除第一个“/”。
然后,您可以将路径名的最后一部分放在一个组中,并将其用作替换的参考</code>。</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre><code>const url = new URL('https://www.test.com/one/two/three/mypost/').pathname.substring(1)
console.log(url.replace(/\/([^/]*)\/$/, '?id='))