How to check whether a string contains any numeric value by 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");
(p/s: my DOM id will be something like Large_a
(without numeric value) , Large_a_1
(with numeric value), Large_a_2
, etc.)
What method should I use?
How to check whether a string contains any numeric value by 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");
(p/s: my DOM id will be something like Large_a
(without numeric value) , Large_a_1
(with numeric value), Large_a_2
, etc.)
What method should I use?
Share Improve this question edited Jul 12, 2011 at 6:28 Zack The Human 8,4818 gold badges42 silver badges61 bronze badges asked Jul 12, 2011 at 6:04 shennyLshennyL 2,79411 gold badges42 silver badges65 bronze badges 1- One of the first google search results: stackoverflow./questions/3955345/… – Adam Tuliper Commented Jul 12, 2011 at 6:15
3 Answers
Reset to default 8You 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):
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);
}
}());