I usually do something like this:
$("#my-div a").click(function(){
var match;
if (match = $(this).attr('id').match(/link-(\d+)/)) {
var number = parseInt(match[1],10);
alert(number);
}
});
This should be the simplest way:
var id = this.id.replace(/[^\d]/g,'')*1;
It returns any digits from the ID attribute as a number
(*1
does the 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')
});
$(this).attr('id').replace('link-','')
$(this).attr('id').split('-')[1];
var id = $(this).attr('id'),
regex = /(\d+)/,
matched = id.match( regex );
if ( matched ) {
alert( matched[1] )
}
You can use a regular expression to parse out the number:
var match = /link-(\d+)/.exec($(this).attr('id'));
var num = match[1];