Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return only text before last underscore in JavaScript string

Tags:

javascript

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'

like image 683
Valor_ Avatar asked Jul 05 '16 16:07

Valor_


People also ask

How do you get the part of a string before a specific character in Javascript?

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.

How can I get part of a string in Javascript?

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.

How do I get text after Javascript?

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.


2 Answers

Slice and lastIndexOf:

str.slice(0, str.lastIndexOf('_'));
like image 78
andrunix Avatar answered Oct 27 '22 18:10

andrunix


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"
like image 37
James Long Avatar answered Oct 27 '22 19:10

James Long