Get number from HTML id using Javascript - Stack Overflow

Alright, so I have an HTML element as <div id="slide_item_#"> where # is a number. What

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 */ ;

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 */ ;
Share Improve this question asked Nov 23, 2010 at 3:52 ChigginsChiggins 8,41723 gold badges57 silver badges81 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 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

var id_number = parseInt(html_id.substr(11));
var html_id = "slide_item_3";
var id_number = +html_id.split('_').pop();

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!)

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745249817a4618609.html

相关推荐

  • Get number from HTML id using Javascript - Stack Overflow

    Alright, so I have an HTML element as <div id="slide_item_#"> where # is a number. What

    5小时前
    20

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信