Replacing strings with regex in JavaScript

2020-04-08 12:00发布

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?

5条回答
我命由我不由天
2楼-- · 2020-04-08 12:42

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

string = string.replace(/range=100/, 'range=400');
查看更多
成全新的幸福
3楼-- · 2020-04-08 12:43

I would do this way

string = string.replace(/\brange=100(?!\d)/, 'range=400');
查看更多
相关推荐>>
4楼-- · 2020-04-08 12:57

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");
查看更多
Juvenile、少年°
5楼-- · 2020-04-08 12:59

Write only string.replace("range=100","range=400");.

查看更多
相关推荐>>
6楼-- · 2020-04-08 13:05

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).

查看更多
登录 后发表回答