How to Remove all Characters Except Numbers in JavaScript

avatar

Borislav Hadzhiev

Last updated: Jul 25, 2022

banner

Check out my new book

Remove all Characters Except Numbers in JavaScript #

To remove all characters except numbers in javascript, call the replace() method, passing it a regular expression that matches all non-number characters and replace them with an empty string. The replace method returns a new string with some or all of the matches replaced.

index.js
const str = 'hello 123 !@#$%^WORLD?456._'; const onlyNumbers = str.replace(/\D/g, ''); console.log(onlyNumbers); // 👉️ 123456

The first parameter we passed to the String.replace method is a regular expression.

We used the g (global) flag to denote that the regular expression should match all occurrences in the string, and not just the first occurrence.

The \D character matches all non-digit characters.

For a complete regex cheatsheet, check out this MDN table.

The second parameter we passed to the replace method is the replacement for each match, in our case an empty string.

The replace method does not change the original string, it returns a new string. Strings are immutable in JavaScript.

For our purposes, we replace all non-digit characters with an empty string in order to remove non-digits from the string.

This wouldn't work if you have floats in your string because the dots . would also get stripped.

If you are trying to preserve a float number by keeping dots in the final result, things can go wrong if the string contains multiple dots or a dot at the wrong place.

If you want to leave dots in the final string to try to preserve float numbers, use the following regex.

index.js
const str = 'hello 123 !@#$%^WORLD?.456_'; const onlyNumbers = str.replace(/[^\d.]/g, ''); console.log(onlyNumbers); // 👉️ 123.456

The caret ^ symbol in the regex means "NOT the following".

We match all non-digits or dots in the example.

The \d character matches all digits in the range [0-9]. However, we prefixed it with a caret ^ (not). So in it's entirety the regex matches all non-digit characters or dots.

As previously noted, things can go wrong if multiple dots exist in the string or a dot is at the wrong place.

Further Reading #

Use the search field on my Home Page to filter through my more than 3,000 articles.