How Can I Change The Last Component Of A Url Path?
Solution 1:
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 $
.
Solution 2:
Split the String by /, remove the last part, rejoin by /, and add the new path
newurl = url.split('/').slice(0,-1).join('/')+'/175'
Solution 3:
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.
Solution 4:
Split the String by /
then change the last part and rejoin by /
:
var newnumber = 175;
var url = "http://something.com:6688/remote/17/26/172";
var segements = url.split("/");
segements[segements.length - 1] = "" + newnumber;
var newurl = segements.join("/");
alert(newurl);
Solution 5:
Depends on what you want to do.
Actually change browser URL:
If you actually want to push the browser to another URL you'll have to use window.location = 'http://example.com/175'
.
Change browser URL hash
If you just want to change the hash you can simply use window.location.hash
.
Re-use the URL on links or similar If you want to reference a URL in links or similar, look into George's answer.
Post a Comment for "How Can I Change The Last Component Of A Url Path?"