TopCoder
TopCoder

Reputation: 4296

Search and replace specific query string parameter value in javascript

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 this above string 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 &.

Upvotes: 44

Views: 59739

Answers (7)

isapir
isapir

Reputation: 23562

The right way to do this is using URLSearchParams rather than RegEx.

  1. Construct a new URLSearchParams from the old Query String
  2. Update the params as needed
  3. call the toString() method to construct an updated Query String.

For example:

var oldUrl = "www.google.com/?test_ref=abc&other=1";

var urlParts = oldUrl.split("?");

var searchParams = new URLSearchParams(urlParts[1]);
searchParams.set("test_ref", "xyz");

var newUrl = urlParts[0] + "?" + searchParams.toString();

console.log("Old URL:", oldUrl);
console.log("New URL:", newUrl);

This is an old question but still comes up at the top of search results

Upvotes: 0

souravb
souravb

Reputation: 121

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.

Upvotes: 2

Roni Tovi
Roni Tovi

Reputation: 886

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.

Upvotes: 1

Nejc Lepen
Nejc Lepen

Reputation: 365

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);
}

Upvotes: 5

Chris
Chris

Reputation: 101

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);
}

Upvotes: 2

Mohamed.Abdo
Mohamed.Abdo

Reputation: 2200

*Java script code to find a specific query string and replace its value *

('input.letter').click(function () {
                //0- prepare values
                var qsTargeted = 'letter=' + this.value; //"letter=A";
                var windowUrl = '';
                var qskey = qsTargeted.split('=')[0];
                var qsvalue = qsTargeted.split('=')[1];
                //1- get row url
                var originalURL = window.location.href;
                //2- get query string part, and url
                if (originalURL.split('?').length > 1) //qs is exists
                {
                    windowUrl = originalURL.split('?')[0];
                    var qs = originalURL.split('?')[1];
                    //3- get list of query strings
                    var qsArray = qs.split('&');
                    var flag = false;
                    //4- try to find query string key
                    for (var i = 0; i < qsArray.length; i++) {
                        if (qsArray[i].split('=').length > 0) {
                            if (qskey == qsArray[i].split('=')[0]) {
                                //exists key
                                qsArray[i] = qskey + '=' + qsvalue;
                                flag = true;
                                break;
                            }
                        }
                    }
                    if (!flag)//   //5- if exists modify,else add
                    {
                        qsArray.push(qsTargeted);
                    }
                    var finalQs = qsArray.join('&');
                    //6- prepare final url
                    window.location = windowUrl + '?' + finalQs;
                }
                else {
                    //6- prepare final url
                    //add query string
                    window.location = originalURL + '?' + qsTargeted;
                }
            })
        });

Upvotes: -1

user578895
user578895

Reputation:

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

Upvotes: 75

Related Questions