admin管理员组

文章数量:1287893

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

: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.

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

http://www.mywebsite./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.

Share Improve this question asked Jun 22, 2009 at 20:56 dougoftheabacidougoftheabaci
Add a ment  | 

4 Answers 4

Reset to default 6

How about this?

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

Use regular expressions ;)

url.replace(/param2:([\d\w])+/, 'param2:new_string')
var key = "param2";
var newKey = "paramX";
var newValue = "valueX";

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

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

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

本文标签: Replacing part of a string with javascriptStack Overflow