4

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?

Zack The Human
  • 8,373
  • 7
  • 39
  • 60
shennyL
  • 2,764
  • 11
  • 41
  • 65
  • One of the first google search results: http://stackoverflow.com/questions/3955345/javascript-jquery-get-number-from-string – Adam Tuliper Jul 12 '11 at 06:15

3 Answers3

8

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];
}
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
3

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]);
}
Mathieu Rodic
  • 6,637
  • 2
  • 43
  • 49
  • There's no need for grouping, *test* is likely more appropriate (*match* returns an array of matches, *test* just tests). So `if (/_\d+$/.test(this.id)) {...}`. Nice catch that the OP may only want trailing numbers. :-) – RobG Jul 12 '11 at 07:11
  • Sorry, I just love short code... and we never know whether the number's value will be needed or not :-) – Mathieu Rodic Jul 12 '11 at 07:16
  • Get it done by: if (ui.draggable.children().attr('id').match(/_(\d+)$/) != null) – shennyL Jul 12 '11 at 09:54
2

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);
    }
}()); 
RobG
  • 142,382
  • 31
  • 172
  • 209
  • I'm curious how much more efficient your closurised version is? I gather that the overhead of the closure is worth it to avoid recreating the regular expression every time? – nnnnnn Jul 12 '11 at 07:30