Get the Index of the First Number in a String in JavaScript

avatar

Borislav Hadzhiev

Last updated: Oct 26, 2021

banner

Photo from Unsplash

Get the Index of the First Number in a String #

To get the index of the first number in a string, call the search() method passing it a regular expression that matches a digit. The search method returns the index of the first match of the regular expression in the string.

index.js
const str = 'hello987'; const indexFirstNumber = str.search(/\d/); console.log(indexFirstNumber); // 👉️ 5 const firstNumber = Number(str[indexFirstNumber]) console.log(firstNumber); // 👉️ 9

We used the String.search method to get the index of the first number in a string.

The only parameter the method takes is a regular expression.

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

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

index.js
const str = 'hello987'; // 👇️ using range 0-9 instead of \d const indexFirstNumber = str.search(/[0-9]/); console.log(indexFirstNumber); // 👉️ 5 const firstNumber = Number(str[indexFirstNumber]) console.log(firstNumber); // 👉️ 9

You can use whichever approach you find more readable.

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

If the regular expression is not matched in the string, the search method returns -1.

index.js
console.log('hello'.search(/[0-9]/)); // 👉️ -1

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

index.js
console.log('hello'[-1]); // 👉️ undefined

If you need to handle the scenario where the string does not contain any numbers, you can use an if statement.

index.js
const str = 'hello987'; const indexFirstNumber = str.search(/[0-9]/); if (indexFirstNumber !== -1) { console.log('✅ string contains at least 1 digit'); const firstNumber = Number(str[indexFirstNumber]); // firstNumber is defined only here } else { console.log('⛔️ string contains no digits'); }

In this example, we only declare the firstNumber 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.