homepage Welcome to WebmasterWorld Guest from
register, free tools, login, search, pro membership, help, library, announcements, recent posts, open posts,
Become a Pro Member

Home / Forums Index / Code, Content, and Presentation / JavaScript and AJAX
Forum Library, Charter, Moderator: open

JavaScript and AJAX Forum

Replacing parameters in URL

 5:34 pm on Sep 8, 2009 (gmt 0)


I am trying to figure out a way to replace query parameters using JS and having a hard time figuring this out. Any help will be greatly appreciated.

In code, get_param identifies st_price but it is unable to replace the string.

_uri = '/default.aspx?&search[st_date]=09/09/2009&search[en_date]=09/10/2009&search[st_rate]=500&search[en_rate]=900';

_new_url = _uri.replace(get_param('search[st_price]'),'search[st_price]'+ui.values[0])

function get_param( name )
name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regexS = "[\\?&]"+name+"=([^&#]*)";
var regex = new RegExp( regexS );
var results = regex.exec( window.location.href );
if( results == null ) return "";
else {
_ret = name+'='+results[1];
return _ret;



 10:40 pm on Sep 8, 2009 (gmt 0)

I'm not very good with regexp's, so I'd use a more JS v1.2 approach using split. It's easier and isn't prone to any problems with a parameter name appearing in a value. I don't know if this really replaces your function, but it may help.

function replace_param(theURL, paramName, newValue) {
var uri_array = theURL.split('?'); // break up URL/query
var params_array = uri_array[1].split('&'); // break up the query
var items_array = new Array;
for (i=0; i<params_array.length; i++) {
items_array = params_array[i].split('='); // split name/value pairs
if (items_array[0] == paramName) {
params_array[i] = items_array[0] + '=' + newValue;
} // end if
} // end for i
return uri_array[0] + '?' + params_array.join('&');
} // end function

Caution: Untested code written on the fly.


 12:40 am on Sep 9, 2009 (gmt 0)

The example _uri does not contain st_price ?

If this is intentional you need to handle this case separately

var oldS = get_param('search[st_price]');
var newS = 'search[st_price]
if ( oldS === "" ) { _new_url = _uri + '&' + newS; }
else { _new_url = _uri.replace(oldS,newS); }


 12:46 am on Sep 9, 2009 (gmt 0)

Thanks DaveVK and rainborick.

I tried rainborick's solution and it worked - no change at all needed. Rainborick, You rock!

Global Options:
 top home search open messages active posts  

Home / Forums Index / Code, Content, and Presentation / JavaScript and AJAX
rss feed

All trademarks and copyrights held by respective owners. Member comments are owned by the poster.
Home ¦ Free Tools ¦ Terms of Service ¦ Privacy Policy ¦ Report Problem ¦ About ¦ Library ¦ Newsletter
WebmasterWorld is a Developer Shed Community owned by Jim Boykin.
© Webmaster World 1996-2014 all rights reserved