如何更改网址路径的最后一个组件?

Mat*_*iby 3 javascript

"http://something.com:6688/remote/17/26/172"
Run Code Online (Sandbox Code Playgroud)

如果我有值172,我需要将网址更改为175

"http://something.com:6688/remote/17/26/175"
Run Code Online (Sandbox Code Playgroud)

我怎么能用JavaScript做到这一点?

Bry*_*eld 20

var url = "http://something.com:6688/remote/17/26/172"
url = url.replace(/\/[^\/]*$/, '/175')
Run Code Online (Sandbox Code Playgroud)

翻译:找到一个斜杠\/,后跟任意数量*的非斜杠字符[^\/],后跟字符串结尾$.

  • 将正则表达式翻译为英语 - 查找一个字符串:一个 / 后面不跟一个 / ,后面跟任意数量的任意字符,最后是字符串的末尾。将其替换为“/175”。一个优秀的正则表达式解决方案。要在 JS 正则表达式中使用 /,它会被转义为 \/ (2认同)
  • 我还会在末尾添加一个可选的 / ,这样它就可以在 .../172 和 .../172/ 中工作,所以它会是: /\/[^\/]*\/?$/ (2认同)

jcs*_*ica 8

new URL("175", "http://something.com:6688/remote/17/26/172").href

\n\n

这也适用于路径,例如

\n\n

new URL("../27", "http://something.com:6688/remote/17/26/172").href\xe2\x86\x92"http://something.com:6688/remote/17/27"

\n\n

new URL("175/1234", "http://something.com:6688/remote/17/26/172").href\xe2\x86\x92"http://something.com:6688/remote/17/26/175/1234"

\n\n

new URL("/local/", "http://something.com:6688/remote/17/26/172").href\xe2\x86\x92\n"http://something.com:6688/local/"

\n\n

有关详细信息,请参阅https://developer.mozilla.org/en-US/docs/Web/API/URL/URL。

\n

  • 这个答案是如此干净,我可以在其中看到我的反映。 (6认同)

com*_*ike 7

用/分割字符串,去掉最后一部分,用/重新连接,添加新路径

newurl = url.split('/').slice(0,-1).join('/')+'/175'
Run Code Online (Sandbox Code Playgroud)