我的最终目标是验证输入字段。输入可以是字母也可以是数字。


当前回答

无论如何,它都不是刀枪不入的,但它对我来说是有效的,也许它会帮助到别人。

var value = $('input').val();
 if(parseInt(value)) {
  console.log(value+" is a number.");
 }
 else {
  console.log(value+" is NaN.");
 }

其他回答

你也可以试试lodash:

const isNumeric = number => 
  _.isFinite(_.parseInt(number)) && !_.isNaN(_.parseInt(number))

如果我没记错的话,这个问题需要“contains number”,而不是“is number”。所以:

function hasNumber(myString) {
  return /\d/.test(myString);
}

这就是你需要的。

      var hasNumber = /\d/;   
      hasNumber.test("ABC33SDF");  //true
      hasNumber.test("ABCSDF");  //false 

当字符串以整数的表示形式开始时,parseInt提供整数:

(parseInt '1a')  is  1

..所以也许:

isInteger = (s)->
  s is (parseInt s).toString()  and  s isnt 'NaN'

(isInteger 'a') is false
(isInteger '1a') is false
(isInteger 'NaN') is false
(isInteger '-42') is true

原谅我的CoffeeScript。

要测试任何字符是否为数字,无需过度修饰❓,可根据需要进行调整。

const s = "EMA618" 函数hasInt(我){ 设I = 1,a = me.split(""),b = "",c = ""; a.forEach(函数(e) { 如果(! isNaN (e)) { console.log(' contains NUMBER«${e}»AT POSITION ${a.indexOf(e)} => TOTAL COUNT ${i} ') C += e 我+ + } else {b += e} }) console.log('字符串是«${b}»,数字是«${c}»') If (i === 0){ 返回假 //返回b }其他{ 还真 //返回+c } } hasInt (s)