Extracting an identifier in all of these cases

How can I always extract the number 11 in all of these cases.

id="section-11" id="test-11" id="something-11" 

I am doing $(this).attr('id'); , then what should I do next?

+4
source share
5 answers

Many ways to achieve this, one way is to use .split() as:

 var id = "section-11"; var number = id.split(/-/)[ 1 ]; alert( number ); // 11 
+6
source
 $(this).attr('id').match(/\d+/)[0] 

This will lead to the first numerical match.

+2
source

Assuming these last two digits are the only numbers in id, replace this regex:

 var id = 'something-11'; var num = id.replace(/\D/g,''); alert(num); 

The above removes all non-numeric characters from the string.

Jsfiddle example

+2
source
 var id = parseInt($(this).attr('id).substring($(this).attr('id').lastIndexOf('-')+1)); 

The above example .split() also works, but you will need to grab the highest index in the array if you specify an identifier with more than 1 dash: subsection-11

0
source

you can divide the string into an array by "-", after which you will get the identifier from the second place of the array.

0
source

All Articles