Amy Buck Haneline
Amy Buck Haneline

Reputation: 11

Jquery: Getting the number from ID

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

Answers (3)

TheCarver
TheCarver

Reputation: 19733

As others have already suggested you can split on the hypen or underscore very simply, using:

var number = str.split("-")[1]

jQuery split() documentation

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+/);

jQuery match() documentation

Upvotes: 1

Joe
Joe

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

Rob W
Rob W

Reputation: 349262

  1. .attr('id') can be used to retrieve the ID attribute.
  2. Then, use the .split function to split the string by a separator.
  3. Get the number from index [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

Related Questions