patternjavascriptCritical
Strip all non-numeric characters from string in JavaScript
Viewed 0 times
fromnumericnoncharactersstringalljavascriptstrip
Problem
Consider a non-DOM scenario where you'd want to remove all non-numeric characters from a string using JavaScript/ECMAScript. Any characters that are in range
How would you achieve this in plain JavaScript? Please remember this is a non-DOM scenario, so jQuery and other solutions involving browser and keypress events aren't suitable.
0 - 9 should be kept.var myString = 'abc123.8';
//desired output is 1238How would you achieve this in plain JavaScript? Please remember this is a non-DOM scenario, so jQuery and other solutions involving browser and keypress events aren't suitable.
Solution
Use the string's
.replace method with a regex of \D, which is a shorthand character class that matches all non-digits:myString = myString.replace(/\D/g,'');Code Snippets
myString = myString.replace(/\D/g,'');Context
Stack Overflow Q#1862130, score: 2005
Revisions (0)
No revisions yet.