1

I have the following string:

http://www.website.com?a=111&b=2222&d=3333

How can I take this string and update the b parameter value with 4444?

3 Answers 3

3
var str = 'http://www.website.com?a=111&b=2222&d=3333';
str.replace(/([&\?]b=\d+/,"$1b=4444")
Sign up to request clarification or add additional context in comments.

1 Comment

what about if it is the first variable in the querystring?
1

String.replace(/b=([^&]*)/, "b=4444")

5 Comments

This will replace "b=2222" with 4444 - which is not what he wants.
This is wrong. It will replace also the b= part so the replacement should be b=4444.
Ahh, of course. I misread my book. Corrected. (No matter how many times I use them, I never quite get the hang of regular expressions.)
Thanks but when I run this through JSHint I get the error "Insecure '^'" - how can I fix this?
I didn't see that error. Perhaps it wants you to replace the & with \& ?
-1
var myString = "http://www.website.com?a=111&b=2222&d=3333".replace("b=2222","b=4444")

2 Comments

I thought the first argument of ".replace" had to be a regex.
Nope. It can be a regular string.

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.