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¶m2=test2. I need to capture complete value not till first &.
You can use the browser's native URL API to do this in a fairly simple way, where key and value are your parameter name and parameter value respectively. const url = new URL(location. href); url. searchParams.
The value of a parameter can be updated with the set() method of URLSearchParams object. After setting the new value you can get the new query string with the toString() method. This query string can be set as the new value of the search property of the URL object.
Query parameters are those funny strings in a URL after the question mark ( ? ). Here's an example of a URL with a query parameter: https://www.
a_href = a_href.replace(/(test_ref=)[^\&]+/, '$1' + updated_test_ref);
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); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With