Return only numbers from string

后端 未结 9 1997
名媛妹妹
名媛妹妹 2021-02-05 07:55

I have a value in Javascript as

var input = \"Rs. 6,67,000\"

How can I get only the numerical values ?

Result: 6

相关标签:
9条回答
  • 2021-02-05 08:28

    You can use

    str.replace('Rs. ', '').replace(/,/g, '');
    

    or

    str.replace(/Rs. |,/g, '');
    
    • /,/g is a regular expression. g means global
    • /Rs. |,/g is a single regular expression that matches every occurence of Rs. or ,
    0 讨论(0)
  • 2021-02-05 08:30

    You can make a function like this

    function justNumbers(string) {
      var numsStr = string.replace(/[^0-9]/g, '');
      return parseInt(numsStr);
    }
    
    var input = "Rs. 6,67,000";
    var number = justNumbers(input);
    console.log(number); // 667000

    0 讨论(0)
  • 2021-02-05 08:33
    var input = "Rs. 6,67,000";
    
    input = input.replace("Rs. ", "");
    
    //loop through string and replace all commas
    while (input.indexOf(",") !== -1) {
        input = input.replace(",","");
    }
    
    0 讨论(0)
  • 2021-02-05 08:35

    You are really close. Change your replace to use the g flag, which will replace all.

    str.replace("Rs. ", "").replace(/,/g,"");
    
    0 讨论(0)
  • 2021-02-05 08:42

    Try this

    var input = "ds. 7,765,000";
    var cleantxt = input.replace(/^\D+/g, '');
    var output = cleantxt.replace(/\,/g, "");
    alert(output);

    0 讨论(0)
  • 2021-02-05 08:43

    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.

    0 讨论(0)
提交回复
热议问题