Reputation: 11
You mentioned this in another question: jquery get number from id
You should get in the habit of using delimiters in your attribute names (ie, button-1, button_1). One of the advantages, of many, is that it makes it easier to extract a number, or some other information, from the field (ie, by splitting the string at '-').
How would you extract the number if you are using a delimiter in your attribute names?
Thanks!
Upvotes: 0
Views: 2693
Reputation: 19733
As others have already suggested you can split on the hypen or underscore very simply, using:
var number = str.split("-")[1]
Another viable option here is to just extract the numbers using regex patterns. This is helpful if the string you're extracting numbers from has no delimeter. I don't use delimeters in my particular style of coding, so this what I use:
var number = str.match(/\d+/);
Upvotes: 1
Reputation: 15812
Replace selector
and delimiter
with your actual values.
var parts = $('#selector').attr('id').split('delimiter');
var my_number = parts[parts.length - 1];
alert(my_number);
Upvotes: 1
Reputation: 349262
.attr('id')
can be used to retrieve the ID attribute..split
function to split the string by a separator.[1]
. Code:
var delimiter = '-';
var num = $("element").attr('id').split(delimiter)[1];
// Expected format: <anything 1>-<anything 2>
// Note that <anything 2> is not necessarily a number
The previous method is very dependent on the id format. A more solid method is a regexp:
var num = /\d+/.exec($("element").attr('id')); // Selects all consecutive digits
// Examples:
// button_1 = 1 button2 = 2 1st = 1 button4--5 = 4
To match the digits at the end, use:
var num = /\d+(?=\D*$)/.exec($("element").attr('id'));
Upvotes: 5