JavaScript / jQuery - capturing integer from element id
From the following markup.
<div id="my-div">
<a href="#" id="link-1">Somewhere</a>
<a href="#" id="link-2">Somewhere else</a>
</div>
What are some options using jQuery and JavaScript selectors to capture an integer in identifiers?
For example.
$("#my-div a").click(function(){
$(this).id // ... somehow grab n from "link-n"
alert(n);
});
+5
10 answers
You may try:
var n = $(this).attr('id').match(/link-(\d+)/)[1];
Acquires an attribute id, matches the pattern link-(\d+)(which means link-followed by one or more digits), and then retrieves the first match of the subexpression (the part in parentheses \d+), which should be the number you are looking for.
n , , parseInt, , 10:
var n = parseInt($(this).attr('id').match(/link-(\d+)/)[1], 10);
id , link-, , , , match:
var match = $(this).attr('id').match(/link-(\d+)/);
if (match) {
var n = parseInt(match[1], 10);
alert(n);
} else {
// do something else if they don't match
}
+4
This should be the easiest way:
var id = this.id.replace(/[^\d]/g,'')*1;
It returns any digits from the ID attribute as number( *1does a conversion similar to parseInt). In your example:
$("#my-div a").click(function(){
var n = this.id.replace(/[^\d]/g,'')*1;
alert(n); // alerts any number in the ID attribute
alert(typeof n) // alerts 'number' (not 'string')
});
0