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: - (

+3


source to share


1 answer


I would suggest:

var stripped = string.replace(/[^0-9\-]/g,'');

      

JS Fiddle demo .

^

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:

+9


source







All Articles