How to Extract/Retrieve a Number From String in JavaScript?


While working with strings in JavaScript, developers frequently come across situations where they need to extract numeric values from within a string. The ability to extract numbers from texts is useful when parsing user input, editing data, or conducting calculations.

This post will describe the methods to extract or retrieve numbers from strings in JavaScript.

How to Extract/Retrieve a Number From String in JavaScript?

The following ways are used for extracting numbers from a string in JavaScript:

  • replace() method with regular expression
  • match() method with regular expression

Method 1: Extract the Number From the String Using the “replace()” method with a Regular Expression

Utilize the “replace()” method with a regular expression or regex pattern for extracting numbers from a string. replace() method will replace or remove all non-digit characters or letters from the string based on regex.

Syntax

The given syntax is used for extracting numbers from strings using the “replace()” method with a regular expression:

string.replace(regex);

Example
Create a string containing a number with text:

const string = 'In lac there are 6 zeros';

Call the replace() method with string and pass the regex or regular expression that accepts only digits/numbers from a string and remove all other characters:

const number = string.replace(/\D/g, '');

Finally, print the resultant string that contains only numbers from a string on the console:

console.log(number);

The output indicates that the number is successfully retrieved from the string:

Method 2: Extract the Number From the String Using the “match()” method with Regular Expression

Another way for extracting a number from a string is to use the “match()” method with the regular expression. match() method matches the string with regex and retrieves all occurrences of numbers within a string.

Syntax

The following syntax is utilized for the match() method to extract a number from a string:

string.match(regex);

Example
First, create a string that contains numbers with alphabets:

const string = 'John buy 5 dozen Banana and 3 dozen Oranges';

Call the match() method by passing the regex pattern for extracting numbers from string and store it in a variable “numbers”:

const numbers = string.match(/\d+/g);

Print the numbers on the console using the “console.log()” method:

console.log(numbers);

Output

That’s all about extracting numbers from strings in JavaScript.

Conclusion

For extracting numbers from a string in JavaScript, utilize the “replace()” method or “match()” method with regular expressions. You may easily extract numeric values from strings in JavaScript by using techniques such as regular expressions, splitting, filtering, or replacing. This post described the methods for extracting or retrieving numbers from strings in JavaScript.

Print Friendly, PDF & Email
Categories