JavaScript extract number from string | RegEx & Replace function example

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>
    <script type='text/javascript'>
        var txt = 'ABC123 XYZ023'
        var num1 = txt.replace(/\D/g,'');


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

This site uses Akismet to reduce spam. Learn how your comment data is processed.