0

我有以下 HTML:

<li class="workorder" id="workorder_7">

我想在一些javascript中使用_之后的数字。在这种情况下,我需要整数 7

我该怎么做?

谢谢!!

4

2 回答 2

4

There are multiple ways to do that: regular expressions, substring matching, and others. One of the easiest is to just use split to break the string into an array, and grab the last array element:

var str_id = "workorder_7";
var id = str_id.split('_')[1];

You can also use .pop as suggested by VisioN to get the last element from the array. Then it would work with a string with any number of underscores, provided the numeric id is the last one:

var str_id = "main_workorder_7";
var id = str_id.split('_').pop();
于 2013-01-09T14:30:51.793 回答
1

另一种方法是使用substring

var str_id = "workorder_7";
var id = str_id.substring(str_id.indexOf('_') + 1);

如果要获取最后一个下划线后面的内容,可以使用:

var str_id = "work_order_id_7";
var id = str_id.substring(str_id.lastIndexOf('_') + 1);
于 2013-01-09T14:31:52.110 回答