3

Hi,

regex is bugging me right now. I simply want to replace the range=100 in a string like

var string = '...commonstringblabla&range=100&stringandsoon...';

with

...commonstringblabla&range=400&stringandsoon...

I successfully matched the "range=100"-part with

alert( string.match(/range=100/) );

But when I try to replace it

string.replace(/range=100/, 'range=400');

nothing happens, the string still has the range=100 in it... I don't get it, please help.

flag

63% accept rate

5 Answers

2

Because replace does not modify the string it is applied on, but returns a new string.

string = string.replace(/range=100/, 'range=400');
link|flag
facepalm that was the problem. thank you. – koko May 10 at 10:56
2

string.replace isn't destructive, meaning, it doesn't change the instance it is called on.

To do this use

string = string.replace("range=100","range=400");
link|flag
1

write only strign.replace("range=100","range=400");

link|flag
1

I would do this:

string.replace(/([?&])range=100(?=&|$)/, '$1range=400')

This will only replace range=100 if it’s a URI argument (so it’s delimited on the left by either ? or & and on the right by & or the end of the string).

link|flag
1

I would do this way

string = string.replace(/\brange=100(?!\d)/, 'range=400');
link|flag

Your Answer

get an OpenID
or
never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.