A particular regular expression is bugging me right now. I simply want to replace the 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?
因为replace
不会修改它所应用的字符串,但会返回一个新字符串。
string = string.replace(/range=100/, 'range=400');
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");
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).
Write only string.replace("range=100","range=400");
.
我会这样做的
string = string.replace(/\brange=100(?!\d)/, 'range=400');
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.