Borislav Hadzhiev
Last updated: Oct 5, 2021
Check out my new book
To extract a number from a string, call the replace
method on the string,
passing in a regular expression to replace all non-digit characters with an
empty string, e.g. str.replace(/\D/g, '')
.
The replace method returns a new string containing all the numbers from the original string.
const str = 'hello 123 world'; const replaced = str.replace(/\D/g, ''); // 👉️ '123' console.log(replaced); let num; if (replaced !== '') { num = Number(replaced); // 👉️ 123 } console.log(num)
The first argument we passed to the String.replace method is a regular expression that we want to match in the string.
The \D
character matches a character that is NOT a digit.
We have added the g
(global) flag to match all non-digit characters and
replace them with an empty string.
String.replace
method would return an empty string.Our if
statement is there to check if the original string contains any
numbers.
If it doesn't we don't want to convert an empty string to a number because that
evaluates to 0
, which would be a bug in our program.
console.log(Number('')); // 👉️ 0
Here is a complete example of the case where the string does not contain numbers:
const str = 'hello world'; const replaced = str.replace(/\D/g, ''); // 👉️ '' console.log(replaced); let num; if (replaced !== '') { // 👇️ never runs num = Number(replaced); } console.log(num); // 👉️ undefined
We replace all non-digit characters with empty strings, and because the string
contains only non-digit characters, String.replace
returns an empty string.
String.replace
method returns a new string, it does not mutate the original string. Strings are immutable in JavaScript.Another common approach, which I would not recommend, is to use the String.match method.
const str = 'hello 123 world'; const replaced = str.match(/\d+/); // 👉️ ['123'] let num; if (replaced !== null) { num = Number(replaced[0]); // 👉️ 123 } console.log(num);
We pass a regular expression to the String.match method.
The \d
character matches a digit from 0
to 9
. We have added the +
character, which means match one or more, to match all digits in the string.
String.match
method is confusing to say the least, but for our purposes, it returns an array containing the match - in our case the string 123
.In case the String.match
method didn't match anything, it returns null
.
To be sure we don't try to convert null
to a number
, which would return 0
,
we conditionally check in our if
statement.
console.log(Number(null)); // 👉️ 0
String.replace
more direct and intuitive than String.match
.For the sake of completeness, here is the case, where the string contains no
digits, when using match
.
const str = 'hello world'; const replaced = str.match(/\d+/); // 👉️ null let num; if (replaced !== null) { // 👇️ never runs num = replaced[0]; } console.log(num); // 👉️ undefined
In the code snippet, the match
method returns null
because the string
contains no digits.