44

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 &.

6
  • 3
    possible duplicate of Replacing strings with regex in JavaScript Commented Mar 24, 2011 at 1:55
  • 1
    This question has been asked a million times. Did you try searching first? Commented Mar 24, 2011 at 1:55
  • no .. its similar but not duplicate. I dont know the value of test_ref ..as its a query string parameter it value changes with different pages.Also i need to replace the value with value of variable updated_test_ref. Its not a fix value.I first need to capture everything following test_ref something like this string.replace(/test_ref=(.*)?/ ) and then just replace the matching part with updated_test_ref value. Commented Mar 24, 2011 at 1:57
  • 1
    Hi Jon.. yes.. I did but i was unable to get what I am looking for in particular. Commented Mar 24, 2011 at 1:58
  • @Jon - See my title update. In light of that and @cwolves's answer, this is not simply a dup of your link (though it might be a dup of something else (haven't looked)) Commented Mar 24, 2011 at 2:10

7 Answers 7

75
a_href = a_href.replace(/(test_ref=)[^\&]+/, '$1' + updated_test_ref);
Sign up to request clarification or add additional context in comments.

6 Comments

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.
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 &
@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.
Actually, I think a better approach would be to use /([?|&]test_ref=)[^\&]+/ as you can have another parameter which ends with test_ref
hi to make it better, how do we make the regular expression case insensitive? @lwburk
|
5

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

1 Comment

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.
2

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

1 Comment

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.
2

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.

3 Comments

garbage code. updateUrlParameter("/fileserver.aspx?mid=1&t=SGK&id=0&f=File2&p=w","id","23954"); returns "/fileserver.aspx?mid=1&t=SGK&id=id=23954&f=File2&p=w"
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);
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.
1

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.

Comments

0

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

Comments

-1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.