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?

1

3 Answers 3

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];
}
Sign up to request clarification or add additional context in comments.

Comments

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]);
}

3 Comments

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. :-)
Sorry, I just love short code... and we never know whether the number's value will be needed or not :-)
Get it done by: if (ui.draggable.children().attr('id').match(/_(\d+)$/) != null)
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);
    }
}()); 

1 Comment

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?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.