开发者

JavaScript regex to replace repeated characters with one

开发者 https://www.devze.com 2023-04-02 09:49 出处:网络
I\'m trying to replace some repeated char开发者_C百科acters using regex: var string = \"80--40\";

I'm trying to replace some repeated char开发者_C百科acters 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.


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


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

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

For more on RegEx, See the MDN documentation


You can specify {x, y} to match any number of repetitions between x and 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消