Borislav Hadzhiev
Tue Oct 26 2021·2 min read
Photo by Joshua Earle
To get the first number in a string:
search()
method to get the index of the first number in the string.search
method takes a regular expression and returns the index of the
first match in the string.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.
search
method does not match any digits in the string, it will return -1
.console.log('test'.search(/[0-9]/)); // 👉️ -1
If you then try to access the string at index -1
, you would get undefined
back.
console.log('test'[-1]); // 👉️ undefined
If you have to handle this scenario, you can use an if
statement.
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.