I want to remove letters from (a1-800-b-400)
, but naively doing so results in (1-800--400)
.
How do I get (1-800-400)
?
If it involves RegExp
, please explain how it works.
I want to remove letters from (a1-800-b-400)
, but naively doing so results in (1-800--400)
.
How do I get (1-800-400)
?
If it involves RegExp
, please explain how it works.
This is the RegExp
you need:
/[^\d\()-]/g
/
/
are simply indicators that you're writing a RegExp
literal.
The trailing g
flag means find all matches, instead of just one.
Everything between the [
]
are the characters you want to match.
But the ^
symbol means the opposite; don't match.
\d
means Number
, \(
means open parenthesis (escaped), )
is obvious, as is -
.
const regExpA = /[^\d\()-]/g;
const regExpB = /--/g;
const string = '(a1-800-b-400)';
const result = string
.replace(regExpA, '') // (1-800--400)
.replace(regExpB, '-'); // (1-800-400)
console.log(result);