Extract a number from a string using JavaScript

In J**aScript, there are multiple ways to extract a number from a string. One way is to use the match() method and a regular expression to search for all numeric digits in the string. Another way is to use the replace() method and a regular expression to...

In J**aScript, there are multiple ways to extract a number from a string. One way is to use the match() method and a regular expression to search for all numeric digits in the string. Another way is to use the replace() method and a regular expression to remove all nonnumeric characters from the string, le**ing only the numbers.

Let’s understand each of the methods with the help of some examples.

Using the match() method and regular expression

The regular expression is one kind of search pattern which we can create by combining multiple alphabetic and special characters. We can use the ‘/\d+/’ search pattern for numbers in the string. In the ‘\d+’ search pattern, d represents the digits between 0 and 9, and ‘+’ represents that find at least one digit.

So, we can use that regular expression as a parameter of the J**aScript built-in match method to search for all digits in the given string.

Syntax

Users can follow the syntax below to extract all numeric digits from the given string.

let str = "Sampll323435 Stringrfd23232ftesd3454!";
let numbers = str.match('/\d+/');

In the above syntax, we h**e used the match() method, which matches the occurrences of the numeric digits in the given string.

Example

In this example, we h**e created the string containing the numbers. After that, we created the regular expression with the g flag to match all occurrences of the numbers in the string and passed it as a parameter of the match() method to match in the string

The match() method returns the array containing all numbers according to the regular expression match.

 
<html> <body> <h3>Using the <i> match () </i> Method and Regular Expression to extract the numbers from the string</h3> <div id = "output"> </div> <script> let output = document.getElementById("output"); // defining the string containing the numbers let str = "Sampll323435 Stringrfd23232ftesd3454!"; output.innerHTML = "Original String: " + str + "<br/>"; // Matching for the numbers using the match() method. let numbers = str.match(/\d+/g); // numbers is an array of all occurrences of numbers // if any single number is **ailable in the string, then print numbers if (numbers.length > 0) { output.innerHTML += "<br> Numbers in the StringL: " + numbers + "<br/>"; } </script> </body> </html>

Using the replace() method and regular expression

We can use the regular expression to identify the numeric character and other characters. So, we will identify the other characters using the regular expression and replace it with the empty string. In such a way, we can remove all characters except numbers and extract numbers from the string.

Syntax

Users can follow the syntax below to extract the numbers from the string using the replace() method.

let result = str.replace(/[^0-9]/g,"");

In the above syntax, str is a reference string from which we wanted to extract a number. Also, the regular expression [^0-9] represents all characters that are not between 0 and 9.

Example

In the example below, we h**e used the replace() method to replace all characters with empty strings except numeric characters. We passed the regular expression as the first parameter and the empty string as the second parameter.

The replace() method returns the string after replacing all characters except the numeric character with an empty string. In the output, we can observe that rather than returning the array like the match() method, it returns only a single string.

 
<html> <body> <h3>Using the <i> replace() </i> method and regular expression to extract the numbers from the string</h3> <div id = "output"> </div> <script> let output = document.getElementById("output"); let string = "dnbdj53454 4k54k6j23in k09e30n9923g9 kjm545"; output.innerHTML = "Original String: " + string + "<br/>"; // replace all non-numeric characters with empty string let result = string.replace(/[^0-9]/g, ""); output.innerHTML +="<br> Numbers in the string: " + result + "<br/>"; </script> </body> </html>

Using the reduce() method to extract the numbers from the string

The reduce() is J**aScript’s built-in library method. We can convert the strings into an array of characters and use the reduce() method with the character’s array. The reduce() method helps us reduce the array to a single element by performing operations on the array elements.

Here, we will check if the character is a number and add it to the final element; otherwise, we will add an empty string.

Syntax

Users can follow the syntax below to use the reduce() method to extract the numbers from the string.

let charArray = [...string];
let numbers = charArray.reduce(function (numString, element) {
   let nums = "0123456789";
   if (nums.includes(element)) {
      return numString + element;
   }
   return numString;
},"");

In the above syntax, we h**e used the reduce method with charArray. We h**e passed the callback function as the first parameter and the empty string as the second parameter.

Algorithm

  • Step 1 − Use the spread operator to convert the string to a characters array.

  • Step 2 − Use the reduce() method with the charArray to reduce the whole array into a single string containing only numbers.

  • Step 3 − Pass the callback function as the first parameter of the reduce() method, which returns the reduced string

  • Step 4 − In the callback function, pass numString as the first parameter, which is a reduced string, and element as a second parameter which is an array element means the character of the string.

  • Step 5 − Inside the callback function, check if the character of the array means the element is between 0 and 9. If so, add the character in the numString and return it; Otherwise, return numString as it is.

  • Step 6 − As a second parameter of reduce() method pass an empty string which is the initial value of the numString.

  • Step 7 − After the full iteration of the array, reduce() method returns the final value of the numString.

Example

In the example below, we h**e taken a string containing the numbers and implemented the above algorithm to extract the numbers from the string.

 
<html> <body> <h3>Using the <i>reduce() </i>method to extract the numbers from the string</h3> <div id = "output"> </div> <script> let output = document.getElementById("output"); let string = "34gr345fr45"; output.innerHTML += "Original String: " + string + "<br/>"; let charArray = [...string]; let numbers = charArray.reduce(function (numString, element) { let nums = "0123456789"; if (nums.includes(element)) { return numString + element; } return numString; }, ""); output.innerHTML +="<br> Number in the String: " + numbers + "<br/>"; </script> </body> </html>

In this tutorial, we discussed three approaches to extracting a number from the given string. The first approach is to use the match() method and a regular expression to search for all numeric digits in the string. The second approach uses the replace() method and a regular expression to remove all non-numeric characters from the string, le**ing only the numbers. The third approach is using the reduce() and includes() method. It is important to carefully consider which method is most suitable for a given situation.

评论0

首页 导航 会员 客服