Rahul Rahul - 1 year ago 81
Javascript Question

How to replace a dynamic value in JavaScript/jQuery?

How can I replace dynamic value in


I have a string like this
myURL = http://www.demo.com?a=1&sp=2&c=3
; I want to replace
with string like 'str=3'. The value of
can change like
, etc.

I am using replace function of jQuery, but I am not sure how can I replace the dynamic value of

myURL.replace("sp=2", "str=3");

Any idea?

Answer Source

Try using regex:

var myURL = "http://www.demo.com?a=1&sp=2&c=3";
var replacementNum = 123;

myURL = myURL.replace(/sp=\d+/g, 'sp=' + replacementNum);


The code above will replace sp= parameter with any number to the given replacement number. It is useful when you don't know sp paramenter value.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download