Remove Non-Numeric in Javascript

#1. Method One

Use the string’s .replace the method with a regex of \D, The RegExp \D Metacharacter is used to search non-digit characters. Which is a replace all non-digits characters:


// a string with non Numeric 
const myString = "123kngk456kngk789";

// replace non-numeric character with ''
var result = myString.replace(/\D/g,'');

// log answer on console
console.log(result);

Result:

123456789

#2. Method Two

Use a regular expression to replace all non-numeric characters from a string. Something like: The [^0-9] expression is used to find any character that is NOT a digit.

// a string with non Numeric 
const myString = "123kngk456kngk789";

// replace non-numeric character with ''
var result = myString.replace(/[^0-9]/g, '');

// log answer on console
console.log(result);

Result:

123456789

Thanks 🙂