...

View Full Version : Javascript regular expression problem



landryraccoon
01-21-2009, 11:44 PM
Hello all,

I am trying to write a simple javascript function that locates a parameter in a url, if it is present, and replace it with a different value. Here's my code:

function setParam(url,param,value) {
var a = '&'+param+'=\d+';
var new_url = url.replace(new RegExp(a), '');
new_url = new_url + '&'+param+'='+value;
return new_url;
}

The problem is, it doesn't work. It adds the new param, value pair to the old url, but the old param isn't replaced. What do I need to do here to make this work?

Thanks for reading.

landryraccoon
01-21-2009, 11:51 PM
Clarification:
If I do setParam("www.mypage.com/?p1=5&name=john","name","rob")

I want to get the output
www.mypage.com/?p1=5&name=rob

instead I get

www.mypage.com/?p1=5&name=john&name=rob

tagnu
01-22-2009, 06:32 AM
Try this:


function setParam(url,param,value) {
var a = '&'+param+'.*[^&]';
var new_value= '&'+param+"="+value;
var new_url = url.replace(new RegExp(a),new_value);
return new_url;
}

Regular expression testing can be done on http://www.quanetic.com/Regex.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum