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'
To get a part of a string, string. substring() method is used in javascript. Using this method we can get any part of a string that is before or after a particular character.
The substr() method extracts a part of a string. The substr() method begins at a specified position, and returns a specified number of characters. The substr() method does not change the original string. To extract characters from the end of the string, use a negative start position.
To get the substring after a specific character, call the substring() method, passing it the index after the character's index as a parameter. The substring method will return the part of the string after the specified character.
Slice and lastIndexOf:
str.slice(0, str.lastIndexOf('_'));
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With