5

If I have a string like so:

var str = 'Arthropoda_Arachnida_Zodariidae_Habronestes_hunti';

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

In this case I want just 'Arthropoda_Arachnida_Zodariidae_Habronestes'

1
  • You can use a RegExp "Arthropoda_Arachnida_Zodariidae_Habronestes_hunti".replace(/(.*)_.*$/g, "$1") Commented Jul 5, 2016 at 16:26

4 Answers 4

11

Slice and lastIndexOf:

str.slice(0, str.lastIndexOf('_'));
Sign up to request clarification or add additional context in comments.

5 Comments

Beat me by 26 seconds
yep! :D you are the winner! :D Fell free to upvote, since i don't wan't to be in -1 ;) I will accept this answer in 8 minuts
Ha James. That always happens to me. Type up a long answer and someone has already answered before me. :)
This doesn't include the last character before the underscore (the "s")
Not sure how you got that Cos. It does for me both in the browser and in Node.
1

Combining substr and lastIndexOf should give you what you want.

var str = "Arthropoda_Arachnida_Zodariidae_Habronestes_hunti";
var start = str.substr(0, str.lastIndexof("_"));
// -> "Arthropoda_Arachnida_Zodariidae_Habronestes"

Comments

1

try this also

var str = "Arthropoda_Arachnida_Zodariidae_Habronestes_hunti";
alert(str.substring(str.lastIndexOf("_")+1)) //to get Last word

alert(str.substring(0,str.lastIndexOf("_")))  //to get first part 

Comments

1

It is possible by using split method:

var s2= 'Arthropoda_Arachnida_Zodariidae_Habronestes_hunti';
var s1= s2.substr(0, s2.lastIndexOf('_')); 

or:

var str = 'Arthropoda_Arachnida_Zodariidae_Habronestes_hunti';
str.split('_',4) 

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.