Remove non-numeric characters except dash
I need to remove all non-digit characters except the dash. This is my attempt (based on: Regex to get all literal fields except comma, dash and single quote ):
var stripped = mystring.replace(/[-0-9]+/g, '');
But this doesn't work: - (
source to share
I would suggest:
var stripped = string.replace(/[^0-9\-]/g,'');
^
in a character class (inside [
and ]
) is a NOT operator, so it matches characters that are not 0-9
or a character (escaped) -
.
As noted in the comment on this answer by Ted Hopp , it shouldn't be avoided -
when it's the last character, but I usually do it to keep this caveat in mind.
Literature:
source to share