\"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/
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 $
.
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);
Try it!
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.
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.
//Alternative way.
var str = window.location.href;
var lastIndex = str.lastIndexOf("/");
var path = str.substring(0, lastIndex);
var new_path = path + "/new_path";
window.location.assign(new_path);
Split the String by /, remove the last part, rejoin by /, and add the new path
newurl = url.split('/').slice(0,-1).join('/')+'/175'