Get the First Number in a String using JavaScript

avatar

Borislav Hadzhiev

Last updated: Oct 26, 2021

banner

Photo from Unsplash

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 #

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.