1

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.

4 Answers 4

6

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/"
Sign up to request clarification or add additional context in comments.

Comments

4

Use regular expressions ;)

url.replace(/param2:([\d\w])+/, 'param2:new_string')

2 Comments

+1 - but can't there be non-digit, non-word-chars following the colon, but preceding the next forward slash?
well, it's just a quick example how to handle this issue. User should adopt it to it's own needs :)
2
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);

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.