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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With