Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 911
Steve Avatar asked Sep 03 '11 15:09

Steve


3 Answers

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

like image 185
Digital Plane Avatar answered Oct 01 '22 21:10

Digital Plane


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

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

For more on RegEx, See the MDN documentation

like image 36
Noobish Avatar answered Oct 01 '22 22:10

Noobish


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.

like image 32
Jeremy Avatar answered Oct 01 '22 22:10

Jeremy