Home > Web Front-end > JS Tutorial > body text

Extract numbers from string using JavaScript

WBOY
Release: 2023-08-26 13:09:21
forward
1682 people have browsed it

使用 JavaScript 从字符串中提取数字

In JavaScript, there are several ways to extract numbers from strings. One way is to use the match() method with a regular expression to search for all numbers in a string. Another way is to use the replace() method and a regular expression to remove all non-numeric characters from the string, leaving only the digits.

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

Use the match() method and regular expressions

A regular expression is a search pattern that we can create by combining multiple letters and special characters. We can use the "/\d /" search pattern to search for numbers in a string. In the '\d' search pattern, d represents a number between 0 and 9, and ' ' represents at least one digit found.

So, we can use this regular expression as an argument to JavaScript’s built-in match method to search for all numbers in a given string.

grammar

Users can extract all numbers from a given string by following the following syntax.

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

In the above syntax, we have used the match() method, which matches the numbers appearing in the given string.

Example

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

The match() method returns an array containing all numbers based on regular expression matching.

<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 available in the string, then print numbers
         if (numbers.length > 0) {
            output.innerHTML += "<br> Numbers in the StringL: " + numbers + "<br/>";
         }
      </script>
   </body>
</html>
Copy after login

Use the replace() method and regular expressions

We can use regular expressions to identify numeric characters and other characters. Therefore, we will use regular expressions to identify other characters and replace them with empty strings. This way we can remove all characters except numbers and extract numbers from the string.

grammar

Users can use the replace() method to extract numbers from strings according to the following syntax.

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

In the above syntax, str is a quoted string from which we want to extract a number. Additionally, the regular expression [^0-9] represents all characters except 0 to 9.

Example

In the following example, we use the replace() method to replace all characters except numeric characters with an empty string. We pass the regular expression as the first parameter and the empty string as the second parameter.

replace() method returns a string after replacing all characters except numeric characters with an empty string. In the output, we can observe that it does not return an array like the match() method, but only returns 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>
Copy after login

Use the reduce() method to extract numbers from a string

reduce() is a built-in library method of JavaScript. We can convert string to character array and use reduce() method on character array. The reduce() method helps us reduce an 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.

grammar

Users can use the reduce() method to extract numbers from strings according to the following syntax.

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

In the above syntax, we use the reduce method with charArray. We pass the callback function as the first parameter and the empty string as the second parameter.

algorithm

  • Step 1 - Convert the string to a character array using the spread operator.

  • Step 2 - Use the reduce() method of charArray to reduce the entire array to 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 simplified string, and element as the second parameter, which is an array element, A string of characters representing a string.

  • Step 5 - In the callback function, check if the characters of the array indicate that the element is between 0 and 9. If so, the character is added to numString and returned; otherwise, numString is returned unchanged.

  • Step 6 - Pass an empty string as the second parameter of the reduce() method, which is the initial value of numString.

  • Step 7 - After a complete iteration of the array, the reduce() method returns the final value of numString.

Example

In the example below, we have taken a string containing numbers and implemented the above algorithm to extract 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>
Copy after login

在本教程中,我们讨论了从给定字符串中提取数字的三种方法。第一种方法是使用 match() 方法和正则表达式来搜索字符串中的所有数字。第二种方法使用 replace() 方法和正则表达式从字符串中删除所有非数字字符,只留下数字。第三种方法是使用reduce()includes()方法。仔细考虑哪种方法最适合特定情况非常重要。

The above is the detailed content of Extract numbers from string using JavaScript. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!