Search and replace specific query string parameter value in javascript

50,991

Solution 1

a_href = a_href.replace(/(test_ref=)[^\&]+/, '$1' + updated_test_ref);

Solution 2

Based on this discussion I have fixed the Chris function (problem with regex string!)

function updateUrlParameter(url, param, value){
    var regex = new RegExp('('+param+'=)[^\&]+');
    return url.replace( regex , '$1' + value);
}

Solution 3

I was searching for this solution for few hours and finally stumbled upon this question. I have tried all the solutions here. But there is still an issue while replacing specific param value in url. Lets take a sample url like

http://google.com?param1=test1&param2=test2&anotherparam1=test3

and the updated url should be like

http://google.com?param1=newtest&param2=test2&anotherparam1=test3, where value of param1 is changed.

In this case, as @Panthro has pointed out, adding [?|&] before the querying string ensures that anotherparam1 is not replaced. But this solution also adds the '?' or '&' character to the matching string. So while replacing the matched characters, the '?' or '&' will also get replaced. You will not know exactly which character is replaced so you cannot append that character as well.

The solution is to match '?' or '&' as preceding characters only.

I have re-written the function of @Chris, fixing the issue with string and have added case insensitive argument.

updateUrlParameter(url, param, value){
    var regex = new RegExp('(?<=[?|&])(' + param + '=)[^\&]+', 'i');
    // return url.replace(regex, param + '=$1' + value);
    return url.replace(regex, param + '=' + value);
}

Here (?<=[?|&]) means, the regex will match '?' or '&' char and will take the string that occurs after the specified character (looks behind the character). That means only param1=test1 substring will be matched and replaced.

Solution 4

Based on this discussion I have created a references function. enjoy

updateUrlParameter(url, param, value){
    var regex = new RegExp("/([?|&]" + param + "=)[^\&]+/");
    return url.replace(regex, '$1' + value);
}

Solution 5

I know this is a bit dirty code but I've achieved what I was looking for. It replaces the given query string or adds new one if it doesn't exist yet.

function updateUrlParameter(url, param, value) {

    var index = url.indexOf("?");

    if (index > 0) {

        var u = url.substring(index + 1).split("&");

        var params = new Array(u.length);

        var p;
        var found = false;

        for (var i = 0; i < u.length; i++) {
            params[i] = u[i].split("=");
            if (params[i][0] === param) {
                params[i][1] = value;
                found = true;
            }
        }

        if (!found) {
            params.push(new Array(2));
            params[params.length - 1][0] = param;
            params[params.length - 1][1] = value;
        }

        var res = url.substring(0, index + 1) + params[0][0] + "=" + params[0][1];
        for (var i = 1; i < params.length; i++) {
            res += "&" + params[i][0] + "=" + params[i][1];
        }
        return res;

    } else {
        return url + "?" + param + "=" + value;
    }

}

It will work when given regular URL addresses like:

updateUrlParameter('https://www.example.com/some.aspx?mid=1&id=2','id','5');
updateUrlParameter('https://www.example.com/?mid=1&id=2','id','5');
updateUrlParameter('https://www.example.com/some.aspx','id','5');

Please note It will NOT work only if any of the query string parameter name or value contains "=" and/or "&" chars. It will work just fine behind that.

Share:
50,991
TopCoder
Author by

TopCoder

Updated on May 09, 2020

Comments

  • TopCoder
    TopCoder about 4 years

    I have a string which is something like this :

    a_href= "www.google.com/test_ref=abc";
    

    I need to search for test_ref=abc in thisabove strinng and replace it with new value

    var updated_test_ref = "xyz";
    
    a_href ="www.google.com/test_ref=updated_test_ref" 
    

    i.e

    www.google.com/test_ref=xyz.
    

    How can we do this ?

    EDIT:

    test_ref value can be a URL link in itself something like http://google.com?param1=test1&param2=test2. I need to capture complete value not till first &.

  • Wayne
    Wayne about 13 years
    Explanation: literally match the string "test_ref=", followed by one or more things that are not the query string parameter separator ("&"), and replace with the captured match ("test_ref="), followed by the value of the variable updated_test_ref.
  • TopCoder
    TopCoder about 13 years
    what happens if my initial test_ref value is something like this = "google.com?ie=UTF8&param1=test1&param2=test2" . please note that test_ref value is also a URL link in itself. I need to capture complete value of test_ref not till first &
  • Wayne
    Wayne about 13 years
    @TopCoder - This is the type of question that doesn't need to be asked. Just get Firebug and test it in the console yourself. "What happens if...?" is almost never a good question. Just try it.
  • Panthro
    Panthro over 12 years
    Actually, I think a better approach would be to use /([?|&]test_ref=)[^\&]+/ as you can have another parameter which ends with test_ref
  • Ryan Ewen
    Ryan Ewen about 10 years
    I had a hard time getting this to work until I realized that you need to remove the leading and ending forward slashes. These are assumed to be there automatically, I guess, and end up doubled if you put them into your string.
  • ylerjen
    ylerjen over 9 years
    Your 2 last comments were just rewriting an accepted answer... Please answer a solved problem only if you have more information to provide than the accepted one. If not, just upvote the accepted answer.
  • Franva
    Franva over 9 years
    hi to make it better, how do we make the regular expression case insensitive? @lwburk
  • Wayne
    Wayne over 9 years
    Simply add the ignorecase (i) flag to the end of the regex, like this: /(test_ref=)[^\&]+/i
  • Roni Tovi
    Roni Tovi about 5 years
    garbage code. updateUrlParameter("/fileserver.aspx?mid=1&t=SGK&id=0&f=File‌​2&p=w","id","23954")‌​; returns "/fileserver.aspx?mid=1&t=SGK&id=id=23954&f=File2&p=w"
  • souravb
    souravb about 5 years
    Have updated a small mistake in this line return url.replace(regex, param + '=$1' + value); I haven't noticed before. thanks for pointing out. The correction will be return url.replace(regex, param + '=' + value);
  • Aakash Goplani
    Aakash Goplani about 4 years
    Positive lookbehind i.e. ?<= is not supported by many browsers. Alternative is to use word boundary i.e. \b. Example queryString.replace(/\bsource=[^&]+/, 'source=' + value), where source is the parameter-name we are interested in.