[英]jQuery - check whether string contains numeric value
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");
我试图找到类似
$(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
(无数值)、 Large_a_1
(有数值)、 Large_a_2
等)
What method should I use?我应该使用什么方法?
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];
}
This code detects trailing digits preceded by the underscore symbol ( azerty1_2 would match "2", but azerty1 would not match):此代码检测以下划线符号开头的尾随数字( azerty1_2将匹配“2”,但azerty1将不匹配):
if (matches = this.id.match(/_(\d)+$/))
{
alert(matches[1]);
}
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);
}
}());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.