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 as开发者_运维问答sume 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 */ ;
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!)
精彩评论