JavaScript RegExp \d Metacharacter - Extract only numbers from a string

← PrevNext →

The RegExp (regular expression) \d Metacharacter in JavaScript is used to match digits from 0 to 9. I am going to use this ES1 feature in my example here to show how to get or extract only numbers from a string.

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.

  <p id='result'></p>

    function getNumber() {
        var str = 'Pi-5778';
        document.getElementById('result').innerHTML= str.match(/\d+/);	   // Result: 5778

Try it

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,

  const getNumber = () => {
    const str = 'Pi-5778-89';
    document.getElementById('result').innerHTML = str.match(/\d+/g);	// Output 5778,89

Try it

It will now perform a "global search" of the string and return all the numbers.

Happy coding. 🙂

← PreviousNext →