How to check if a string contains a number in JavaScript?

前端 未结 8 1356
粉色の甜心
粉色の甜心 2021-01-13 18:37

I don\'t get how hard it is to discern a string containing a number from other strings in JavaScript.

Number(\'\') evaluates to 0, while

相关标签:
8条回答
  • 2021-01-13 19:07

    No need to panic just use this snippet if name String Contains only numbers or text. try below.

    var pattern = /^([^0-9]*)$/;
    if(!YourNiceVariable.value.match(pattern))   {//it happen while Name Contains only Charectors.}
    
    if(YourNiceVariable.value.match(pattern))   {//it happen while Name Contains only Numbers.}
    
    0 讨论(0)
  • 2021-01-13 19:08

    This might be insane depending on the length of your string, but you could split it into an array of individual characters and then test each character with isNaN to determine if it's a number or not.

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