【问题标题】:Is there any function for checking the string parameter contains only numbers or not in JavaScript? [duplicate]在 JavaScript 中是否有用于检查字符串参数是否仅包含数字的函数? [复制]
【发布时间】:2020-06-13 19:14:33
【问题描述】:

我需要创建一个将参数作为字符串获取的函数,并检查该字符串参数是否仅包含数字。我试过这样做,但我不确定 REGEX 的值。

function validateNum(x) {
  var regex = /^\d+$/

  var isValid = regex.test(x.value);
  if (isValid) {
    console.log("This is a Number. Thus, Accepted!.");
  } else {
    console.log("Only Numbers allowed.");
  }
  return isValid;
}
console.log(validateNum("12x3aj")) //Only Numbers allowed.
console.log(validateNum("12345")) //This is a Number. Thus, Accepted!.

谁能帮我解决这个问题?

【问题讨论】:

  • 字符串没有value 属性。只需使用regex.test(x)

标签: javascript regex string function


【解决方案1】:

看来你想要Array.from(myString).every(Number.isInteger)之类的东西。

【讨论】:

    猜你喜欢
    • 2010-12-19
    • 2012-03-27
    • 1970-01-01
    • 2018-07-07
    • 1970-01-01
    • 1970-01-01
    • 2013-11-20
    相关资源
    最近更新 更多