Rahul Rahul - 5 months ago 9
Javascript Question

How to replace a dynamic value in JavaScript/jQuery?

How can I replace dynamic value in

javascript/jquery
?

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

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


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


Any idea?

Answer

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);

Demo

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.

Comments