Skip to content

JavaScript extract number from string | RegEx & Replace function example

  • by

How to get numeric value from string JavaScript?

Simply use a regular expression in the replace function to get numbers from the string in JS. Regular expression for extracting a number is (/(\d+)/).

string.replace(/[^0-9]/g, '');

This will delete all non-digit characters, leaving only digits in the string

Example of JavaScript extract number from string

Here is HTML example code, Regular expression will serve your purpose:

Where txt is given string (with number). It basically rips off anything that is not a digit

<!DOCTYPE html>
<html>
<head>
    <script type='text/javascript'>
        var txt = 'ABC123 XYZ023'
        var num1 = txt.replace(/\D/g,'');
        alert(num1);
    </script>
</head>
<body>
</body>
</html>

Output:

JavaScript extract number from string

\D matches a character that is not a numerical digit. So any non-digit is replaced by an empty string. The result is only the digits in a string.

The g at the end of the regular expression literal is for “global” meaning that it replaces all matches and not just the first.

This approach will work for a variety of input formats, so if that "Rs." becomes something else later, this code won’t break.

Do comment if you have another code or any doubts on this tutorial.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Your email address will not be published. Required fields are marked *