开发者

Extract a number from a string using jQuery

I have a series of records with ids 开发者_如何学Goassigned to them. I.e.

record1, record2, record3 etc

I'm trying to get the id of the link being clicked using:-

$("a.removeTier").live('click', function() {
    var tier = $(this).attr('id').match('/\d+$/');
    alert(tier);
});

The variable tier, should only contain the numeric value within the string. Currently, I'm getting null.

Any ideas?


Why not just use slice() or substring()?

 var tier = this.id.slice(6);
 // -> 1, 2, 3... 11... 123, etc

Example - http://jsfiddle.net/TmBQ8/

PS, you're getting null at the moment because you're passing a string argument to match, instead of a regular expression. Remove the quotes, e.g. match(/\d+$/). Also note in my example, I skipped using a jQuery wrapper and attr() since it's the long way around and not as efficient as direct property access.


If your id always has "record" in front of it then...

$("a.removeTier").live('click', function() {
    var tier = $(this).attr('id').subString("6");
    alert(tier);
});

If you change the word "record" to something else just change the 6 the the position of the first number.


Using a blunter object:

$(this).attr('id').substring("6","7")

As noted in comments, this only works for one-digit numbers. So do this instead:

$(this).attr('id').replace("record", "") 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜