Welcome to WebmasterWorld Guest from 54.145.209.107

Forum Moderators: open

Replacing parameters in URL

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

10+ Year Member



Folks,

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)

WebmasterWorld Senior Member 10+ Year Member



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)

WebmasterWorld Senior Member 5+ Year Member



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]='+ui.values[0];
if ( oldS === "" ) { _new_url = _uri + '&' + newS; }
else { _new_url = _uri.replace(oldS,newS); }

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

10+ Year Member



Thanks DaveVK and rainborick.

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

 

Featured Threads

My Threads

Hot Threads This Week

Hot Threads This Month