For example, I have a string variable "Pi-5778". I want to extract only the numbers (or digits) from the string. Its very simple.
See this example.
<body> <p id='result'></p> </body> <script> function getNumber() { var str = 'Pi-5778'; document.getElementById('result').innerHTML= str.match(/\d+/); // Result: 5778 } getNumber(); </script>
The "d" in /\d+/ is lowercase. Remember, regular expressions are case sensitive. The output or the result will change entirely if not used properly.
To get numbers (only) from the string, I am using a method called .match(). This built-in method takes a parameter in the form of a "pattern". The pattern is "/\d+/".
So far, so good.
Now, let use assume I have another string value, "Pi-5778-89" and I want to extract all the numbers, like 5778 and 89.
However, using the above pattern ("/\d+/") the output will be "5778". Because, regexp "/\d+/" will return only the first occurance of the numbers.
Therefore, I need the g modifier to do a "global" search. Like this,
<script> const getNumber = () => { const str = 'Pi-5778-89'; document.getElementById('result').innerHTML = str.match(/\d+/g); // Output 5778,89 } getNumber(); </script>
It will now perform a "global search" of the string and return all the numbers.