Tags
Asked 2 years ago
16 Jun 2021
Views 198
john

john posted

Extract number from string in JavaScript

Extract number from string in JavaScript
Mahesh Radadiya

Mahesh Radadiya
answered Apr 27 '23 00:00

To extract a number from a string in JavaScript, you can use regular expressions and the match() method.

Here's an example:



const str = "abc 123 def";
const number = str.match(/\d+/);
console.log(number[0]); // Output: "123"

In this example, the regular expression /\d+/ matches one or more digits (\d+) in the string. The match() method returns an array of all the matches, which in this case only contains one element, the matched number. We can access that number using the index [0] of the resulting array.

If there are multiple numbers in the string and you want to extract a specific one, you can use the index of the match like this:


const str = "abc 123 def 456 ghi";
const number = str.match(/\d+/)[1];
console.log(number); // Output: "456
"
In this example, we use the index [ 1 ] to access the second number matched by the regular expression. If there were more numbers, you could adjust the index accordingly.

Note that if the string does not contain any numbers, the match() method will return null. You should check for this case and handle it appropriately, such as by setting a default value or throwing an error.
Post Answer