views:

194

answers:

4

Let's say I have a URL that looks something like this:

http://www.mywebsite.com/param1:set1/param2:set2/param3:set3/

I've made it a varaible in my javascript but now I want to change "param2:set2" to be "param2:set5" or whatever. How do I grab that part of the string and change it?

One thing to note is where "param2..." is in the string can change as well as the number of characters after the ":". I know I can use substring to get part of the string from the front but I'm not sure how to grab it from the end or anywhere in the middle.

+2  A: 

Use regular expressions ;)

url.replace(/param2:([\d\w])+/, 'param2:new_string')
Mantas
+1 - but can't there be non-digit, non-word-chars following the colon, but preceding the next forward slash?
Faisal Vali
well, it's just a quick example how to handle this issue. User should adopt it to it's own needs :)
Mantas
+2  A: 

How about this?

>>> var url = 'http://www.mywebsite.com/param1:set1/param2:set2/param3:set3/';
>>> url.replace(/param2:[^/]+/i, 'param2:set5'); 
"http://www.mywebsite.com/param1:set1/param2:set5/param3:set3/"
Paolo Bergantino
A: 

You can pass regular expressions to the match() and replace() functions in javascript.

Bayard Randel
+1  A: 
var key = "param2";
var newKey = "paramX";
var newValue = "valueX";

var oldURL = "http://www.mywebsite.com/param1:set1/param2:set2/param3:set3/";

var newURL = oldURL.replace( new RegExp( key + ":[^/]+" ), newKey + ":" + newValue);
Clint