Monday, April 27, 2009

In my project, i have a requirement that we need to get url from the browser and depends on user selection, or some criteria we need to change some querystring values and reload the page with new url. Here is a small function which will do that in javascript.
function replaceQueryString(url, param, value) {
var preURL = "";
var postURL = "";
var newURL = "";

var start = url.indexOf(param+"=");
if(start > -1)
{
var end = url.indexOf("=", start);
preURL=url.substring(0,end) +"="+value;

var startRest = url.indexOf("&",start);
postURL="";
if(startRest > -1)
{
postURL=url.substring(startRest);
}
}
else
{
var delimeter = "";
preURL=url;
if (url.indexOf("?") > 0)
delimeter = '&';
else
delimeter = '?';

postURL=delimeter+param+"="+value;
}
newURL = preURL+postURL;
var index = newURL.indexOf('id=',0);
if(index > -1)
{
var Nurl = newURL.substring(0,index);
var EUrl = newURL.substr(index,newURL.length - index);
var eIndex = EUrl.indexOf('&',0);
if(eIndex > -1)
EUrl = EUrl.substr(eIndex, EUrl.length - eIndex);
//newURL = newURL.substring();
newURL = Nurl + EUrl;
}
return newURL;
}   
the newUrl which builds the new url with updated querystring values.

2 comments:

  1. function replaceQueryString(url, param, value) {
    var preURL = "";
    var postURL = "";
    var newURL = "";

    var start = url.indexOf(param+"=");
    if(start > -1)
    {
    var end = url.indexOf("=", start);
    preURL=url.substring(0,end) +"="+value;

    var startRest = url.indexOf("&",start);
    postURL="";
    if(startRest > -1)
    {
    postURL=url.substring(startRest);
    }
    }
    else
    {
    var delimeter = "";
    preURL=url;
    if (url.indexOf("?") > 0)
    delimeter = '&';
    else
    delimeter = '?';

    postURL=delimeter+param+"="+value;
    }
    newURL = preURL+postURL;

    return newURL;
    }

    that worked for me.

    thanks a lot:)

    ReplyDelete
  2. I love you, this is amazing

    ReplyDelete