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

avatar

Borislav Hadzhiev

Tue Oct 26 20212 min read

banner

Photo by Spencer Davis

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 #

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