how to get numeric value from string?

前端 未结 5 909
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-02-08 23:54

This will alert 23.

alert(parseInt(\'23 asdf\'));

But this will not alert 23 but alerts NaN

alert(parseInt(\'asdf 23\'));


        
相关标签:
5条回答
  • 2021-02-09 00:06

    You have to use regular expression to extract the number.

    var mixedTextAndNumber= 'some56number';
    var justTheNumber = parseInt(mixedTextAndNumber.match(/\d+/g));
    
    0 讨论(0)
  • 2021-02-09 00:11
    function toNumeric(string) {
        return parseInt(string.replace(/\D/g, ""), 10);
    }
    
    0 讨论(0)
  • 2021-02-09 00:16

    You can use a regex to get the first integer :

    var num = parseInt(str.match(/\d+/),10)
    

    If you want to parse any number (not just a positive integer, for example "asd -98.43") use

    var num = str.match(/-?\d+\.?\d*/)
    

    Now suppose you have more than one integer in your string :

    var str = "a24b30c90";
    

    Then you can get an array with

    var numbers = str.match(/\d+/g).map(Number);
    

    Result : [24, 30, 90]

    For the fun and for Shadow Wizard, here's a solution without regular expression for strings containing only one integer (it could be extended for multiple integers) :

    var num = [].reduce.call(str,function(r,v){ return v==+v?+v+r*10:r },0);
    
    0 讨论(0)
  • 2021-02-09 00:24
    parseInt('asd98'.match(/\d+/))
    
    0 讨论(0)
  • 2021-02-09 00:24
    var num = +('asd98'.replace(/[a-zA-Z ]/g, ""));
    
    0 讨论(0)
提交回复
热议问题