最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Get number from HTML id using Javascript - Stack Overflow

programmeradmin0浏览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 */ ;

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!)
发布评论

评论列表(0)

  1. 暂无评论