Categories
JavaScript Answers

How to Strip All Non-Numeric Characters from a String in JavaScript?

Spread the love

Stripping all non-numeric characters from a string is something that we do sometimes in our JavaScript apps.

In this article, we’ll look at how to strip all non-numeric characters from a string with JavaScript.

String.prototype.replace

To strip all non-numeric characters from a string in JavaScript, we can use the string replace method to find all non-numeric characters and replace them with empty strings.

For instance, we can write:

const str = 'abc123'
const newStr = str.replace(/D/g, '');
console.log(newStr)

to call replace with a regex to get all non-numeric characters and replace them with an empty string.

D mean non-numeric characters.

And g means we search for all instances of the given pattern in the string.

Therefore, newStr is '123' .

Also, we can use the 0-9 pattern to search for digits. so we can write:

const str = 'abc123'
const newStr = str.replace(/[^0-9]/g, '');
console.log(newStr)

And so we get the same result as the previous example.

To leave decimal points and negative signs in the string, we can do a more precise replacement by writing:

const str = 'abc123.45'
const newStr = str.replace(/[^d.-]/g, '');
console.log(newStr)

^d.- means we search for anything other than digits, decimal points, and the negative sign and replace them all with empty strings.

So newStr is ‘123.45’ .

Conclusion

We can use the string’s replace instance method to strip all non-numeric characters from a string with JavaScript.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *