Borislav Hadzhiev
Tue Oct 26 2021·2 min read
Photo by Spencer Davis
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.
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]
.
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
.
console.log('hello'.search(/[0-9]/)); // 👉️ -1
If you try to access a string at index -1
, you would get undefined
back.
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.
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.