javascript jQuery - 检查字符串是否包含数值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6660107/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 21:27:24  来源:igfitidea点击:

jQuery - check whether string contains numeric value

javascriptjquery

提问by shennyL

How to check whether a string contains any numeric value by jquery?

如何通过jquery检查字符串是否包含任何数值?

I search through many examples but I only get the way to check for a number, NOT number in a STRING. I am trying to find something like $(this).attr('id').contains("number");

我搜索了许多示例,但我只能找到检查数字的方法,而不是 STRING 中的数字。我试图找到类似的东西$(this).attr('id').contains("number");

(p/s: my DOM id will be something like Large_a(without numeric value) , Large_a_1(with numeric value), Large_a_2, etc.)

(p/s:我的 DOM id 将类似于Large_a(without numeric value) , Large_a_1(with numeric value) Large_a_2, 等)

What method should I use?

我应该使用什么方法?

采纳答案by Mathieu Rodic

This code detects trailing digits preceded by the underscoresymbol (azerty1_2would match "2", but azerty1would not match):

此代码检测以下划线符号开头的尾随数字(azerty1_2将匹配“2”,但azerty1不匹配):

if (matches = this.id.match(/_(\d)+$/))
{
    alert(matches[1]);
}

回答by Darin Dimitrov

You could use a regular expression:

您可以使用正则表达式:

var matches = this.id.match(/\d+/g);
if (matches != null) {
    // the id attribute contains a digit
    var number = matches[0];
}

回答by RobG

Simple version:

简单版:

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

More efficient version (keep regular expression in a closure):

更高效的版本(在闭包中保留正则表达式):

var hasNumber = (function() {
    var re = /\d/;
    return function(s) {
      return re.test(s);
    }
}());