Extract a number from a string using JavaScript
The number from a string in javascript can be extracted into an array of numbers by using the match method. This function takes a regular expression as an argument and extracts the number from the string. Regular expression for extracting a number is (/(\d+)/).
Example 1: This example uses match() function to extract number from string.
<!DOCTYPE html> <html> <head> <title> Extract number from string </title> </head> <body > <div align="center" style="background-color: green;"> <h1>GeeksforGeeks</h1> <p>String is "jhkj7682834"</p> <p id="GFG"> Click the button to extract number </p> <input type="button" value="click " onclick="myGeeks()"> </div> <script> function myGeeks() { var str = "jhkj7682834"; var matches = str.match(/(\d+)/); if (matches) { document.getElementById('GFG').innerHTML = matches[0]; } } </script> </body> </html> |
Output:
- Before Clicking the button:

- After Clicking the button:

Example 2: This example uses match() function to extract number from string.
<!DOCTYPE html> <html> <head> <title> Extract number from string </title> </head> <body> <div align="center" style="background-color: green;"> <h1>GeeksforGeeks</h1> <p>String is "foo35bar5jhkj88"</p> <h3> The string contains 3 numbers. So the numbers are stored in an array and print together </h3> <p id="GFG"> Click the button to extract number </p><br> <h3 id="Geeks"></h3> <input type="button" value="Click Here!" onclick="myGeeks()"> </div> <script> function myGeeks() { var str = "foo35bar5jhkj88"; matches = str.match(/\d+/g); var i=0 document.getElementById('GFG').innerHTML = matches[0] + matches[1] + matches[2]; document.getElementById("Geeks").innerHTML = "Where 35 is the first, 5 is the second" + " and 88 is the third number" } </script> </body> </html> |
Output:
- Before Clicking the button:

- After Clicking the button:

Recommended Posts:
- Perl | Extract IP Address from a String using Regex
- JavaScript | Difference between String.slice and String.substring
- JavaScript | Check if a string is a valid JSON string
- How to count string occurrence in string using JavaScript?
- JavaScript | Insert a string at position X of another string
- How to extract img src and alt from html using PHP?
- PHP | extract() Function
- JavaScript | string.toString()
- JavaScript | string.substring()
- JavaScript | String indexOf()
- JavaScript | String split()
- JavaScript | String toLowerCase()
- JavaScript | string.normalize()
- JavaScript | String toUpperCase()
- JavaScript | String lastIndexOf()
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



