0

Suppose you have this string: url?param1=something&param2=something&param3=something which can also be only url?param1=something.

How would you do to convert param1=something to param1=anotherthing ?

I am able to do it this way:

var regex = /param1=.*(&|$)/;
var string = 'url?param1=something&param2=something&param3=something';
var newValue = 'anotherthing';
string.replace(regex, 'param1='+newValue);

However, I do not like the fact of repeating all the search term, so I'm asking if it is possible to group the needed pattern to replace, in this case would be .* and replace only that.

For example, saying that $1 belongs to group 1. This is fictitious.

var regex = /param1=(.*)(&|$)/;
var string = 'url?param1=something&param2=something&param3=something';
var newValue = 'anotherthing';
string.replace(regex, $1, newValue);

2 Answers 2

2

Try this:

var string = 'url?param1=something&param2=something&param3=something';
alert(string.replace(/(param1)([^&]+)/, '$1=newparam1'));

if you want to set multiple parameters to the same value

alert(string.replace(/(param1|param2)([^&]+)/g, '$1=newparam'));
Sign up to request clarification or add additional context in comments.

Comments

0

Add another capture group...

var regex = /(param1=)([^&]*)/;
var string = 'url?param1=something&param2=something&param3=something';
var newValue = 'anotherthing';
string.replace(regex, "$1" + newValue);

2 Comments

Hey thanks, your example gives me "url?param1=anotherthing" instead of the full url, any tip?
Whoops, I did not pay attention to your reg exp, it should have been /(param1=)([^&]*)/;

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.