0

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?

0

2 Answers 2

3

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.

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

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

Sign up to request clarification or add additional context in comments.

1 Comment

@Rahul glad to help!
0

you need to assign it back to myURL

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

replace will return a value, it won't change the myURL value on its own.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.