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

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

我搜索了很多例子,但我只能检查一个数字,而不是STRING中的数字。 我试图找到像$(this).attr('id').contains("number");

(p / s:我的DOM ID类似于Large_a (没有数值), Large_a_1 (带数值), Large_a_2等)

我应该使用什么方法?

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

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

您可以使用正则表达式:

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

简单版本:

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

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

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