How to Extract a Number from a String in JavaScript?

Estimated read time 2 min read

To extract a number from a string in JavaScript, you can use a combination of regular expressions and built-in string methods. Here are some ways to achieve this:

  1. Using regular expressions and the match method:
const str = 'I have 3 apples';
const num = str.match(/\d+/)[0]; // returns '3'

This code uses the regular expression \d+ to match one or more digits in the string. The match method returns an array of all matches, so we access the first element of the array to get the matched number as a string.

  1. Using the parseInt function:
const str = 'The price is $42.99';
const num = parseInt(str.match(/\d+/)[0]); // returns 42

In this code, we use parseInt to convert the matched string to a number. parseInt will return the first number it finds in the string, so we still need to use a regular expression to extract the number.

  1. Using the Number function:
const str = 'The temperature is -10°C';
const num = Number(str.match(/-?\d+/)[0]); // returns -10

This code is similar to the previous example, but it also handles negative numbers. The regular expression /-?\d+/ matches an optional minus sign followed by one or more digits. We use the Number function to convert the matched string to a number.

Note that all of these examples assume that there is only one number in the string. If the string contains multiple numbers, you may need to adjust the regular expression or use a different method to extract the number you need.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply