How to Extract a Number from a String in JavaScript

avatar
Borislav Hadzhiev

Last updated: Dec 21, 2022
7 min

banner

# Table of Contents

  1. Extract a Number from a String in JavaScript
  2. Get the First Number in a String in JavaScript
  3. Get the Number from the End of a String in JavaScript

# Extract a Number from a String in JavaScript

Use the String.replace() method to extract a number from a string, e.g. str.replace(/\D/g, '').

The String.replace() method will extract a number from the string by replacing all non-digit characters with empty strings.

index.js
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)

extract number from string

The replace method returns a new string containing all the numbers in the original string.

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 any character that is NOT a digit.

We added the g (global) flag to match all non-digit characters and replaced them with empty strings.

If the string only contains non-digit characters, we would replace all of them with empty strings and the String.replace method would return an empty string.

The if statement is there to check if the 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.

index.js
console.log(Number('')); // ๐Ÿ‘‰๏ธ 0

Here is a complete example of a case where the string doesn't contain numbers.

index.js
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.

Note that the String.replace method returns a new string, it doesn't mutate the original string. Strings are immutable in JavaScript.

# Extract a number from a String using String.match()

Another commonly used approach, which I wouldn't recommend, is to use the String.match method.

index.js
const str = 'hello 123 world'; const replaced = str.match(/\d+/); // ๐Ÿ‘‰๏ธ ['123'] let num; if (replaced !== null) { num = Number(replaced[0]); // ๐Ÿ‘‰๏ธ 123 } console.log(num);

extract number from string using match

We passed a regular expression to the String.match method.

The \d character matches a digit from 0 to 9.

The + is used to match one or more of the preceding characters (the digits in the range 0-9).

The return value of the String.match method is confusing, but for our purposes, it returns an array containing the match.

If the String.match() method doesn't match anything, it returns null.

The if statement is there to make sure we don't try to convert null to a number, which would return 0.

index.js
console.log(Number(null)); // ๐Ÿ‘‰๏ธ 0

Which approach you pick is a matter of personal preference. I find the approach using String.replace() more direct and intuitive.

Here is an example of a case where the string contains no digits when using String.match().

index.js
const str = 'hello world'; const replaced = str.match(/\d+/); // ๐Ÿ‘‰๏ธ null let num; if (replaced !== null) { // ๐Ÿ‘‡๏ธ never runs num = replaced[0]; } console.log(num); // ๐Ÿ‘‰๏ธ undefined

The String.match() method returns null because the string contains no digits.

# Get the First Number in a String in JavaScript

To get the first number in a string:

  1. Use the search() method to get the index of the first number in the string.
  2. Access the string at the index.
  3. Convert the character to a number.
index.js
// โœ… get the first digit in a string function getFirstDigit(str) { const index = str.search(/[0-9]/); return Number(str[index]); } console.log(getFirstDigit('one 2 three 4')); // ๐Ÿ‘‰๏ธ 2 console.log(getFirstDigit('a 100 b 200')); // ๐Ÿ‘‰๏ธ 1 // -------------------------------------------------- // โœ… get the first number in a string function getFirstNumber(str) { const match = str.match(/[0-9]+/); return parseInt(match[0]); } console.log(getFirstNumber('one 2 three 4')); // ๐Ÿ‘‰๏ธ 2 console.log(getFirstNumber('a 100 b 200')); // ๐Ÿ‘‰๏ธ 100

get first number in string

The first code sample uses the String.search method to get the index of the first digit in the string.

The only parameter the method takes is a regular expression.

The forward slashes / / mark the beginning and end of the regular expression.

The part between the square brackets [] is called a character class and matches a range of digits from 0 to 9.

index.js
function getFirstDigit(str) { const index = str.search(/[0-9]/); return Number(str[index]); }

The next step is to access the string at the index and convert the character to a number.

If the search method doesn't match any digits in the string, it will return -1.
index.js
console.log('test'.search(/[0-9]/)); // ๐Ÿ‘‰๏ธ -1

If you then try to access the string at index -1, you would get undefined back.

index.js
console.log('test'[-1]); // ๐Ÿ‘‰๏ธ undefined

If you have to handle this scenario, use an if statement.

index.js
const str = 'one 2 three 4'; const index = str.search(/[0-9]/); if (index !== -1) { console.log('โœ… String contains at least 1 number'); const firstNum = Number(str[index]); // firstNum is defined only here } else { console.log('โ›”๏ธ String does not contain any numbers'); }

We only declare the firstNum variable if the search() method matches at least 1 digit in the string.

# Get the first number in a string using String.match()

If you need to match more than one digit, use the String.match() method.

index.js
function getFirstNumber(str) { const match = str.match(/[0-9]+/); return parseInt(match[0]); } console.log(getFirstNumber('one 2 three 4')); // ๐Ÿ‘‰๏ธ 2 console.log(getFirstNumber('a 100 b 200')); // ๐Ÿ‘‰๏ธ 100

The String.match method matches a string against a regular expression.

The method returns an array containing the matches (if any) or null if no matches are found.

index.js
const str = 'a 100 b 200'; // ๐Ÿ‘‡๏ธ [ '100', index: 2, input: 'a 100 b 200', groups: undefined ] console.log(str.match(/[0-9]+/));

The plus + matches the preceding item (the 0-9 range) 1 or more times.

The last step is to access the array at index 0 and convert the string to a number.

Note that the match() method will return null if the string doesn't contain any numbers.

index.js
const str = 'abc'; // ๐Ÿ‘‡๏ธ null console.log(str.match(/[0-9]+/));

If you need to handle this scenario, use an if/else statement.

index.js
const str = 'a 100 b 200'; const match = str.match(/[0-9]+/); const num = parseInt(match[0]); if (num !== null) { console.log('The string contains a number'); console.log(num); // ๐Ÿ‘‰๏ธ 100 } else { console.log('The string does NOT contain any numbers'); }

The if block is only run if the string contains a number, otherwise, the else block runs.

We used the [0-9] character class to match digits in the string, however, you might also see examples online that use the \d special character.

index.js
const str = 'one 2 three 4'; const index = str.search(/\d/); console.log(index); // ๐Ÿ‘‰๏ธ 4 const firstNum = Number(str[index]); console.log(firstNum); // ๐Ÿ‘‰๏ธ 2

The \d special character matches any digit from 0 to 9. Specifying the \d character is the same as specifying a range of [0-9].

index.js
function getFirstNumber(str) { const match = str.match(/\d+/); return parseInt(match[0]); } console.log(getFirstNumber('one 2 three 4')); // ๐Ÿ‘‰๏ธ 2 console.log(getFirstNumber('a 100 b 200')); // ๐Ÿ‘‰๏ธ 100

If you ever need help reading a regular expression, check out this regular expression cheatsheet by MDN.

It contains a table with the name and the meaning of each special character with examples.

# Get the Number from the End of a String

Use the String.match() method to get the number from the end of a string, e.g. str.match(/[0-9]+$/);.

The match method will return an array containing the number from the end of the string at index 0.

index.js
function getNumberFromEnd(str) { const matches = str.match(/[0-9]+$/); if (matches) { return parseInt(matches[0], 10); } return null; } // ๐Ÿ‘‡๏ธ 456 console.log(getNumberFromEnd('one 2 three 456')); // ๐Ÿ‘‡๏ธ 987 console.log(getNumberFromEnd('bobbyhadz 987'));

The String.match method matches a string against a regular expression.

The method returns an array containing the matches (if any) or null if no matches are found.

The only parameter the method takes is a regular expression.

The forward slashes / / mark the beginning and end of the regular expression.

The square brackets [] part is called a character class and matches a range of digits from 0 to 9.

The plus + matches the preceding item (the digits range) one or more times.

The dollar sign $ matches the end of the input.

The match() method returns an array containing the matches.

index.js
const str = 'one 2 three 456'; // ๐Ÿ‘‡๏ธ [ '456', index: 12, input: 'one 2 three 456', groups: undefined ] const match = str.match(/[0-9]+$/); const result = parseInt(match[0]); console.log(result); // ๐Ÿ‘‰๏ธ 456

Once we have the array containing the matches, we use the parseInt function to parse the string into a number.

If the regular expression is not matched in the string (the string contains no digits at the end), the match() method will return null.
index.js
const str = 'one 2 three 456 seven'; const arr = str.match(/[0-9]+$/); console.log(arr); // ๐Ÿ‘‰๏ธ null

If you need to handle this scenario, you can use an if statement.

index.js
const str = 'one 2 three 456 seven'; const arr = str.match(/[0-9]+$/); console.log(arr); // ๐Ÿ‘‰๏ธ null let num; if (arr !== null) { console.log('โœ… String contains digits at the end'); num = parseInt(arr[0], 10); } else { // ๐Ÿ‘‡๏ธ this runs console.log('โ›”๏ธ String contains NO digits at the end'); }

In this example, we only call the parseInt function if the string contains digits at the end.

If you try to access a nullue at index 0, you would get an error, so it's much safer to have a conditional in place.

We used the [0-9] character class in the examples, however, you can also use the \d special character.

index.js
function getNumberFromEnd(str) { // ๐Ÿ‘‡๏ธ using \d special character const matches = str.match(/\d+$/); if (matches) { return parseInt(matches[0], 10); } return null; } // ๐Ÿ‘‡๏ธ 456 console.log(getNumberFromEnd('one 2 three 456')); // ๐Ÿ‘‡๏ธ 987 console.log(getNumberFromEnd('bobbyhadz 987'));

The \d character matches any digit from 0 to 9.

The special character is equivalent to the [0-9] character class.

If you ever need help reading a regular expression, check out this regular expression cheatsheet by MDN.

It contains a table with the name and the meaning of each special character with examples.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.

Copyright ยฉ 2024 Borislav Hadzhiev