Return only numbers from string

This is a great use for a regular expression.

    var str = "Rs. 6,67,000";
    var res = str.replace(/\D/g, "");
    alert(res); // 667000

\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.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)