Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing strings with regex in JavaScript

A particular regular expression is bugging me right now. I simply want to replace the range=100 in a string like

var string = '...commonstringblabla<b>&range=100&</b>stringandsoon...';

with

...commonstringblabla<b>&range=400&</b>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. How can I make it work?

like image 743
koko Avatar asked Dec 08 '22 03:12

koko


2 Answers

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");
like image 119
Sean Kinsey Avatar answered Dec 14 '22 09:12

Sean Kinsey


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

string = string.replace(/range=100/, 'range=400');
like image 45
Vincent Robert Avatar answered Dec 14 '22 07:12

Vincent Robert