0

Alright, so I have an HTML element as <div id="slide_item_#"> where # is a number. What I would like to do, using Javascript, is get the number from the id. So I would assume a regular expression, I just don't know how to use them in Javascript.

var html_id = "slide_item_3";
var id_number = /* code here so that id_number == 3 */ ;

4 Answers 4

5

I would just parse the string without the prefix using parseInt(), like this:

var id_number = parseInt(html_id.replace('slide_item_',''), 10);

An improvement, if you have the option, would involve naming your classes for your element the same as your id (i.e., "slide_item"), except that your id would have the correct number appended to the end (i.e., "slide_item2"). Then, in your code, you would simply use this.className instead of explicitly using 'slide_item_', and the rest of this code would be more dynamic

Sign up to request clarification or add additional context in comments.

Comments

2
var id_number = parseInt(html_id.substr(11));

2 Comments

No code example that includes parseInt can be complete without the advice to always use parseInt(string, 10) (i.e. specify the radix 10) because otherwise, a leading zero (as in "010") will cause the number to be interpreted as octal.
+1 though because your code performs the best of the three answers in so far. jsperf.com/get-number-from-id
2
var html_id = "slide_item_3";
var id_number = +html_id.split('_').pop();

1 Comment

To clarify how this works, .split('_') turns the string into an array, .pop() removes and returns the last element of that array, and + at the beginning casts the result to a numeric value.
0

if you don't know the prefix or suffix... you only want the ID number:

var id_number = html_id.replace(/\D+/,""); // Remove all non-digit characters

will result in:

var html_id = "slide_item_3"  // 3  
var html_id = "foo45bar"      // 45
var html_id = "1-item-X"      // 1
var html_id = "1-item-2"      // 12 (take care of such cases!)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.