Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove non numeric characters except dash

Tags:

javascript

I need to remove all non numeric characters except the dash. This is my attempt (based on: Regex to get all alpha numeric fields except for comma, dash and single quote):

var stripped = mystring.replace(/[-0-9]+/g, '');

But that doesn't work :-(

like image 259
user3142695 Avatar asked Oct 05 '14 13:10

user3142695


1 Answers

I'd suggest:

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

JS Fiddle demo.

^ in the character class (within the [ and ]) is the NOT operator, so it matches characters which are not 0-9 or the (escaped) - character.

As noted in the comment to this answer, by Ted Hopp, it's not necessary to escape the - when it's the last character, but I habitually do so in order to save having to remember that proviso.

References:

  • JavaScript Regular Expressions.
like image 151
David Thomas Avatar answered Sep 22 '22 20:09

David Thomas