JQuery - check if a string contains a numeric value

How to check if a string contains any jquery numeric value?

I look through a lot of examples, but I only get the opportunity to check the number, not the number in STRING. I am trying to find something like $(this).attr('id').contains("number");

(p / s: my DOM identifier will look like Large_a (without a numeric value), Large_a_1 (with a numeric value), Large_a_2 , etc.)

Which method to use?

+4
source share
3 answers

This code detects trailing digits preceded by an underscore ( azerty1_2 matches "2", but azerty1 does not match):

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

You can use regex:

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

Simple version:

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

More efficient version (keep regex in closure):

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

All Articles