Somewhere

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
source share
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).attr('id').replace('link-','')

+2

, substring, .

$(this).attr('id').substring(5)
+2

, :

// id contains '1' for id="link-1"
var id = parseInt(this.id.replace(/[^\d]/g, ''), 10);
+1

- :

$("#my-div a").click(function(){
    var match;
    if (match = $(this).attr('id').match(/link-(\d+)/)) {
      var number = parseInt(match[1],10);
      alert(number);
    }
});
+1
var id = $(this).attr('id'),
    regex = /(\d+)/,
    matched = id.match( regex );

if ( matched ) {
    alert( matched[1] )
}
+1
$(this).attr('id').split('-')[1];
+1

If you know that all of your identifiers are prefixed with "link-", you can simply get the id substring:

$("#my-div a").click(function(){
   alert(this.id.substr(5));
});
0
source

You can use regular expression to parse the number:

var match = /link-(\d+)/.exec($(this).attr('id'));
var num = match[1];
0
source

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
source

All Articles