sameold
sameold

Reputation: 19242

Extracting the id in all these cases

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

Answers (5)

vexy
vexy

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

minboost
minboost

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

Mark Biek
Mark Biek

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.

jsfiddle example

Upvotes: 2

John Strickler
John Strickler

Reputation: 25421

$(this).attr('id').match(/\d+/)[0]

This will pull the first numeric match.

Upvotes: 2

jAndy
jAndy

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

Related Questions