Search and replace specific query string parameter value in javascript

后端 未结 6 1596
无人及你
无人及你 2020-12-23 20:07

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 stri

6条回答
  •  旧时难觅i
    2020-12-23 20:57

    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¶m2=test2&anotherparam1=test3

    and the updated url should be like

    http://google.com?param1=newtest¶m2=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.

提交回复
热议问题