Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
150
rated 0 times [  155] [ 5]  / answers: 1 / hits: 17637  / 10 Years ago, sun, october 5, 2014, 12:00:00

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


More From » javascript

 Answers
142

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:




[#69240] Thursday, October 2, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
harleyterryp

Total Points: 290
Total Questions: 92
Total Answers: 95

Location: Montenegro
Member since Sun, May 7, 2023
1 Year ago
;