Check if character is number?

前端 未结 22 762
误落风尘
误落风尘 2020-12-03 00:29

I need to check whether justPrices[i].substr(commapos+2,1).

The string is something like: \"blabla,120\"

In this case it would check whether \'0

22条回答
  •  无人及你
    2020-12-03 00:52

    A simple solution by leveraging language's dynamic type checking:

    function isNumber (string) {
       //it has whitespace
       if(string.trim() === ''){
         return false
       }
       return string - 0 === string * 1
    }
    
    

    see test cases below

    function isNumber (str) {
       if(str.trim() === ''){
         return false
       }
       return str - 0 === str * 1
    }
    
    
    console.log('-1' + ' → ' + isNumber ('-1'))    
    console.log('-1.5' + ' → ' + isNumber ('-1.5')) 
    console.log('0' + ' → ' + isNumber ('0'))    
    console.log(', ,' + ' → ' + isNumber (', ,'))  
    console.log('0.42' + ' → ' + isNumber ('0.42'))   
    console.log('.42' + ' → ' + isNumber ('.42'))    
    console.log('#abcdef' + ' → ' + isNumber ('#abcdef'))
    console.log('1.2.3' + ' → ' + isNumber ('1.2.3')) 
    console.log('' + ' → ' + isNumber (''))    
    console.log('blah' + ' → ' + isNumber ('blah'))

提交回复
热议问题