Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I change the last component of a url path?

Tags:

javascript

"http://something.com:6688/remote/17/26/172"

if I have the value 172 and I need to change the url to 175

"http://something.com:6688/remote/17/26/175"

how can i do that in JavaScript?

like image 379
Matt Elhotiby Avatar asked Oct 26 '10 16:10

Matt Elhotiby


2 Answers

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

Translation: Find a slash \/ which is followed by any number * of non slash characters [^\/] which is followed by end of string $.

like image 125
700 Software Avatar answered Oct 22 '22 21:10

700 Software


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

This also works with paths, e.g.

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

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

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

See https://developer.mozilla.org/en-US/docs/Web/API/URL/URL for details.

like image 44
jcsahnwaldt Reinstate Monica Avatar answered Oct 22 '22 21:10

jcsahnwaldt Reinstate Monica