0

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

2 Answers 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();
Sign up to request clarification or add additional context in comments.

2 Comments

@dfsq I'm assuming OP is using a fixed format for the id attributes. But if it's not fixed, you can always assign the return from split in a var and use .length-1 as the index.
I'd better use .split("_").pop() instead.
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.