JavaScript 正则表达式用一个替换重复的字符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7294153/
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-25 23:37:46  来源:igfitidea点击:

JavaScript regex to replace repeated characters with one

javascriptregex

提问by Steve

I'm trying to replace some repeated characters using regex:

我正在尝试使用正则表达式替换一些重复的字符:

var string = "80--40";
string = string.replace(/-{2}/g,"-");    // result is "80-40"

This replaces two minuses with one, but how could I change the code so that it replaces two or more? I only want one minus symbol to appear between the numbers.

这用一个替换了两个减号,但是我如何更改代码以替换两个或多个?我只希望数字之间出现一个减号。

回答by Digital Plane

Change it to:

将其更改为:

string = string.replace(/-{2,}/g,"-");

Another way is

另一种方式是

string = string.replace(/-+/g,"-");

as that replaces any one or more instances of -with only one -.

因为-它只用一个-.

回答by Noobish

{2}matches exactly two, +matches one or more.

{2}正好匹配两个,+匹配一个或多个。

string = string.replace(/\-+/g, '-');

For more on RegEx, See the MDN documentation

有关 RegEx 的更多信息,请参阅 MDN 文档

回答by Facebook Staff are Complicit

You can specify {x, y}to match any number of repetitions between xand y. You can also leave off the upper or lower bound, so use {2,}instead of {2}to replace any matches that occur at least two times.

您可以指定{x, y}x和之间匹配任意数量的重复y。您也可以不设置上限或下限,因此使用{2,}而不是{2}替换至少出现两次的任何匹配项。