You are currently viewing 2 Simple Methods to Extract Number from String in JavaScript

2 Simple Methods to Extract Number from String in JavaScript

Extract Number from String in JavaScript

When working with text data in JavaScript, it’s common to encounter situations where you need to extract numbers from a string. This could be for processing user input, parsing data from an external source, or any number of other use cases. Fortunately, JavaScript provides several methods for extracting numbers from a string. In this article, we’ll explore some common approaches for extract numbers from a string in JavaScript:

Using regular expressions

To extract a number from a string in JavaScript, we can use the ‘match()’ method of a string object along with a regular expression. The regular expression is ‘/\d+/g’, matches one or more digits (\d+) globally (g) in the string. The match() method returns an array of all matches found in the string.

const string = "Jo3hn2310";
const numbers = string.match(/\d+/g);
console.log(numbers);

// Output : ['3', '2310']

Using the parseFloat or parseInt functions:

We can also use parseFloat() or parseInt() method with regular expression. The parseFloat and parseInt functions are built-in functions for parsing strings and extracting numeric values. If you want to return a floating-point number from a string you can use parseFloat(). If you want to return an integer number from a string, you can use parseInt(). In this approach, we first use a regular expression to extract the number, and then we pass the extracted string to either ‘parseFloat()’ or ‘parseInt()’ to get the numeric value.

const str = "My balance is $10.5";
const bal= parseFloat(str.match(/\d+\.\d+/));
console.log(bal);

// Output: 10.5
const str = "The price of apple is $5";
const price = parseInt(str.match(/\d+/g));
console.log(price);

// Output: 5

Conclusion

These are just a few examples of extracting numbers from a string in JavaScript. The best approach depends on the specific requirements of your application.

Leave a Reply