最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - jQuery - check whether string contains numeric value - Stack Overflow

programmeradmin5浏览0评论

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
Add a ment  | 

3 Answers 3

Reset to default 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];
}

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);
    }
}()); 
发布评论

评论列表(0)

  1. 暂无评论