Search and replace specific query string parameter value in javascript

TopCoder picture TopCoder · Mar 24, 2011 · Viewed 46.3k times · Source

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

Answer

Mark Kahn picture Mark Kahn · Mar 24, 2011
a_href = a_href.replace(/(test_ref=)[^\&]+/, '$1' + updated_test_ref);