How to get the first number in a string using JavaScript
Get the first number in a string
To get the first number in a string, we can use the String.match() method by passing a regular expression /[0-9]+/
. It returns an array with the first matched number.
Here is an example:
const str = "My house no 234 located in denmark";
const firstNumber = str.match(/[0-9]+/);
console.log(firstNumber); // ["234"]
// You can extract number from the array using spread operator
console.log(...firstNumber); // "234"
In the example above, we have used the String.match() to get a first digit in the string.
The regular expression /[0-9]+/
, where [0-9] matches the digits ranging from 0-9.
The +
character matches the precending 1 or more digits.
If we don’t provide +
it only returns the first matched number eg: from 234 it only returns 2.
Currently, we are not doing any null check in our code. For example, if a given string doesn’t contain any number it means we need to log some output instead of error in console. To handle this case, we can use if else condtion.
const str = "My house no 234 located in denmark";
const firstNumber = str.match(/[0-9]+/);
if(firstNumber){
console.log(...firstNumber); // "234"
}else{
console.log("String doesn't have any numbers");
}
Now, if a given string doesn’t contain any numbers we are logging a destructive message in the console instead of error.