14

If I have a string like so:

var str = 'Arthropoda_Arachnida_Zodariidae_Habronestes_hunti';

How can I get just the last part of the string after the last underscore?

And in the case there are no underscores just return the original string.

In this case I want just 'hunti'

1

3 Answers 3

31
var index = str.lastIndexOf("_");
var result = str.substr(index+1);
Sign up to request clarification or add additional context in comments.

4 Comments

IMO prefer this method. The other method requires more memory and more processing. It has to create the array, just to get the last item, and then throw away the rest of the array. Not a huge deal in the example you posted, but this method is two lines instead of one and I think equally as readable and functional. So I'd prefer this answer to the rest.
This method is less aesthetically pleasing to me, as it feels somewhat verbose, but I willingly admit that it is faster. Unless he has very long strings and he's doing this thousands of times, though, I doubt it will make a perceptible difference.
@EliGassert—peformance is unlikely to be an issue, but you're correct that substring is much faster than the other methods proposed. It just depends on how the OP wants to approach it.
This answer is correct, but you don't need to do the steps separately. str.substring(str.lastIndexOf('_') + 1);
15

It's very simple. Split the string by the underscore, and take the last element.

var last = str.split("_").pop();

This will even work when the string does not contain any underscores (it returns the original string, as desired).

Comments

4

You can use a regular expression:

'Arthropoda_Arachnida_Zodariidae_Habronestes_hunti'.match(/[^_]*$/)[0];

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.