8

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.

3 Answers 3

17

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

Sign up to request clarification or add additional context in comments.

Comments

8

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

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

For more on RegEx, See the MDN documentation

Comments

2

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.