Search code examples
javascriptsearchreplacedesign-patternsmatch

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


Solution

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