user275074
user275074

Reputation:

Extract a number from a string using jQuery

I have a series of records with ids assigned 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?

Upvotes: 1

Views: 4859

Answers (3)

morgancodes
morgancodes

Reputation: 25265

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", "") 

Upvotes: 0

Capt Otis
Capt Otis

Reputation: 1260

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.

Upvotes: 0

Andy E
Andy E

Reputation: 344497

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.

Upvotes: 7

Related Questions