javascript JS正则表达式替换数字

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11730688/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 14:10:06  来源:igfitidea点击:

JS regex replace number

javascriptregex

提问by Matthew Ruddy

Trying to get my head around some regex using JS .replace to replace an integer with a string.

尝试使用 JS .replace 用字符串替换整数来解决一些正则表达式。

For example, the string could be:

例如,字符串可以是:

var string = 'image[testing][hello][0][welcome]';

I want to replace the '0' with another value. I was originally using this:

我想用另一个值替换“0”。我最初使用的是这个:

string.replace( /\[\d\]/g, '[newvalue]');

But when we start replacing double digits or more (12, 200, 3204, you get what I mean), it stops working properly. Not sure how to get it functioning the way I want it too.

但是当我们开始替换两位数或更多(12、200、3204,你明白我的意思)时,它会停止正常工作。不知道如何让它以我想要的方式运行。

Thanks in advance. Greatly appreciated.

提前致谢。非常感激。

回答by David says reinstate Monica

You need to specify multiple digits:

您需要指定多个数字:

string.replace( /\[\d+\]/g, '[newvalue]');

JS Fiddle demo

JS小提琴演示

(Note the demo uses jQuery to iterate through the nodes, but it's merely a convenience, and has no bearing on the regular expression, it just demonstrates its function.)

(注意该演示使用 jQuery 来遍历节点,但这只是为了方便,与正则表达式无关,只是演示了它的功能。)

The reason your original didn't work, I think, was because \dmatches only a single digit, whereas the +operator/character specifies the preceding (in this case digit) character one or more times.

我认为您的原件不起作用的原因是因为\d只匹配一个数字,而+运算符/字符一次或多次指定前面的(在本例中为数字)字符。

Reference:

参考:

回答by codename-

Use the following:

使用以下内容:

string.replace( /\[\d+\]/g, '[newvalue]');

string.replace( /\[\d+\]/g, '[newvalue]');

That should match all digits in brackets.

这应该匹配括号中的所有数字。