View Full Version : Javascript regular expression problem

01-21-2009, 10: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.

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

I want to get the output

instead I get


01-22-2009, 05: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