Get the First Number in a String using JavaScript

avatar

Borislav Hadzhiev

Tue Oct 26 20212 min read

banner

Photo by Joshua Earle

Get the First Number in a String #

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. The search method takes a regular expression and returns the index of the first match in the string.
  3. Access the string at the index, using bracket notation.
index.js
const str = 'one 2 three 4'; const index = str.search(/[0-9]/); console.log(index); // ๐Ÿ‘‰๏ธ 4 const firstNum = Number(str[index]); console.log(firstNum); // ๐Ÿ‘‰๏ธ 2

We used 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.

The next step is to access the string at the specific index using bracket notation and convert the string to a number.

If the search method does not 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, you can 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'); }

In this example, we only declare the firstNum variable if the search method matched at least 1 digit in the string.

Further Reading #

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee