dougoftheabaci
dougoftheabaci

Reputation:

Replacing part of a string with javascript?

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.

Upvotes: 1

Views: 5649

Answers (4)

Clint
Clint

Reputation: 9058

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);

Upvotes: 2

Bayard Randel
Bayard Randel

Reputation: 10086

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

Upvotes: 0

Paolo Bergantino
Paolo Bergantino

Reputation: 488584

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/"

Upvotes: 6

Mantas
Mantas

Reputation: 5951

Use regular expressions ;)

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

Upvotes: 4

Related Questions