Can anyone tell me, how can I remove all non-numeric characters from strings in JavaScript?
For example, I get textContent from DOM, where I have a text like “ID NO. 94854112”. So how can I keep the only numbers and remove all the other characters? Keep only 94854112.
You can use the string’s replace()
method with a regex. \D
is a shorthand character class that matches all characters except digits. So you can replace all characters with ''
empty string except digits.
let someID = "ID NO. 94854112";
console.log( someID.replace(/\D/g, '') );
// Result : 94854112
OR you can try this example below as well.
let someID = "ID NO. 94854112";
console.log( someID.replace(/[^0-9]/g, '') );
// Result : 94854112