I want to replace +
-
(
)
and space
with an empty character in a Javascript string. The expression I'm using is:
"+1 - (042) - 123456".replace(/[\+\-\' '\(\)]/, "");
which results in:
"1 - (042) - 123456"
Only the +
is replaced and not the other characters. What is the error in my expression?
I want to replace +
-
(
)
and space
with an empty character in a Javascript string. The expression I'm using is:
"+1 - (042) - 123456".replace(/[\+\-\' '\(\)]/, "");
which results in:
"1 - (042) - 123456"
Only the +
is replaced and not the other characters. What is the error in my expression?
-
1
Most characters in a class don't need escaping:
[-+'() ]
– georg Commented Jul 11, 2015 at 9:01 -
1
Note that if you want to strip out all non-digits could use
\D
the negation of\d
which is a short for[0-9]
: Replace/\D+/g
with empty string (besides the reason why it failed which is answered already). – Jonny 5 Commented Jul 11, 2015 at 11:01
4 Answers
Reset to default 5When you use square brackets to list characters to remove/change or whatever, you don't want to escape them. And I would remend using \s
instead of , and, of course, you need the global flag -
g
.
"+1 - (042) - 123456".replace(/[+()\s-]/g, "")
Use the g flag:
/[\+\-\' '\(\)]/g
JS:
"+1 - (042) - 123456".replace(/[\+\-\' '\(\)]/g, "");
The g
indicates a "Global search", meaning that every match of the regex must be replaced.
You need to include g
global flag inorder to make pattern to match two or more times on the same line. And alo you don't need to include single quotes inside the character class.
"+1 - (042) - 123456".replace(/[-+() ]/g, "");
As idmean mentioned in their answer , you should add the g(global) flag , otherwise the function will stop once the first match is found .
However , there are some redundant escapes and characters in your RegEx.
That's how your RegEx can be in its simplest form :
/[+) (-]/g
I didn't get why there are single quotes in your RegEx.