"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)
翻译:找到一个斜杠\/,后跟任意数量*的非斜杠字符[^\/],后跟字符串结尾$.
new URL("175", "http://something.com:6688/remote/17/26/172").href
这也适用于路径,例如
\n\nnew URL("../27", "http://something.com:6688/remote/17/26/172").href\xe2\x86\x92"http://something.com:6688/remote/17/27"
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"
new URL("/local/", "http://something.com:6688/remote/17/26/172").href\xe2\x86\x92\n"http://something.com:6688/local/"
有关详细信息,请参阅https://developer.mozilla.org/en-US/docs/Web/API/URL/URL。
\n用/分割字符串,去掉最后一部分,用/重新连接,添加新路径
newurl = url.split('/').slice(0,-1).join('/')+'/175'
Run Code Online (Sandbox Code Playgroud)