How to Extract Numbers from Strings in JavaScript?

Estimated read time 1 min read

You can extract numbers from strings in JavaScript by using regular expressions and the match() method.

Here’s an example:

var str = "My age is 30";
var numbers = str.match(/\d+/g);

In this example, the match() method is used to extract all the occurrences of one or more consecutive digits (\d+) from the string stored in the str variable. The regular expression is enclosed in /.../ delimiters, and the g flag is used to perform a global search for all matches. The resulting array of numbers is stored in the numbers variable, which can be logged to the console or used elsewhere in your code.

Note that if there are no numbers in the string, the match() method will return null. In this case, you can check the value of numbers before using it, or you can use a conditional statement to handle the null case.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply