最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Replacing strings with regex in JavaScript - Stack Overflow

programmeradmin3浏览0评论

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

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

with

..monstringblabla<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?

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

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

with

...monstringblabla<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?

Share Improve this question edited Sep 2, 2010 at 17:40 Peter Mortensen 31.6k22 gold badges110 silver badges133 bronze badges asked May 10, 2010 at 10:42 kokokoko 95812 silver badges26 bronze badges
Add a ment  | 

5 Answers 5

Reset to default 6

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");

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

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

I would do this way

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

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

发布评论

评论列表(0)

  1. 暂无评论