简体   繁体   中英

JavaScript regex to replace repeated characters with one

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.

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.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM