tags:

views:

49

answers:

4
"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?

+1  A: 

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 @cjavapro answer.

Frankie
+6  A: 
var url = "http://something.com:6688/remote/17/26/172"
url = url.replace(/\/[^\/]*$/, '/175')
cjavapro
cjavapros solution is pretty neat , even if the values changes it will work
gov
Translating the regexp to English--find a string: a / which is not followed by a / which is followed by any number of any characters which is followed by the end of the string. Replace it with "/175". An excellent regexp solution. To use a / in JS regexp, it is escaped as \/
Larry K
A: 

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!

Adam
@Adam , don't mind but i think regex replace might be very simple for this kind of pattern replaces
gov
@gov, I agree. I regex is simpler and a better solution. The only advantage of my approach is readability
Adam
@adam , yes we can understand whats happening with the code
gov
A: 

You can't actually change the URL that is shown in the address bar with javascript without a page refresh. If this was possible it would represent a fairly substantial security issue in my opinion. If you can live with a page refresh, window.location is your best option.

If you are using jQuery, the jQuery BBQ plugin is pretty neat. It handles a lot of the hard work for you.

Icode4food