Reddirt
Reddirt

Reputation: 5953

javascript select the part of a string

I have the following HTML:

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

I would like to use the digit after the _ in some javascript. In this case, I need the integer 7

How would I do that?

Thanks!!

Upvotes: 0

Views: 169

Answers (2)

bfavaretto
bfavaretto

Reputation: 71939

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();

Upvotes: 4

user1726343
user1726343

Reputation:

Another way is to use substring:

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

If you want to get the content following the last underscore, you can use:

var str_id = "work_order_id_7";
var id = str_id.substring(str_id.lastIndexOf('_') + 1);

Upvotes: 1

Related Questions