Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 687
TopCoder Avatar asked Mar 24 '11 01:03

TopCoder


People also ask

How can I add or update a query string parameter?

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.

How do I change the parameters in a URL?

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.

What is query parameter in Javascript?

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.


2 Answers

a_href = a_href.replace(/(test_ref=)[^\&]+/, '$1' + updated_test_ref); 
like image 165
Nobody Avatar answered Sep 25 '22 12:09

Nobody


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); } 
like image 27
Nejc Lepen Avatar answered Sep 25 '22 12:09

Nejc Lepen