Reputation: 19242
How can I always extract the number 11 in all these cases.
id="section-11"
id="test-11"
id="something-11"
I do $(this).attr('id');
then what do I do next?
Upvotes: 4
Views: 91
Reputation: 1
you can split the string to an array by "-", then you will get the id from the second place of the array.
Upvotes: 0
Reputation: 2563
var id = parseInt($(this).attr('id).substring($(this).attr('id').lastIndexOf('-')+1));
The .split()
example above also works, but you'll need to grab the highest index in the array, in case you name an id with more than 1 dash: sub-section-11
Upvotes: 0
Reputation: 150749
Assuming that those last two digits are going to be the only numbers in the id, here's a regex replace to do it:
var id = 'something-11';
var num = id.replace(/\D/g,'');
alert(num);
The above deletes all non-numeric characters from the string.
Upvotes: 2
Reputation: 25421
$(this).attr('id').match(/\d+/)[0]
This will pull the first numeric match.
Upvotes: 2
Reputation: 235972
Many ways to achieve that, one way is to use .split()
like:
var id = "section-11";
var number = id.split(/-/)[ 1 ];
alert( number ); // 11
Upvotes: 6