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'
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'
-
You can use a
RegExp
"Arthropoda_Arachnida_Zodariidae_Habronestes_hunti".replace(/(.*)_.*$/g, "$1")
– user6445533 Commented Jul 5, 2016 at 16:26
4 Answers
Reset to default 11Slice 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"
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
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)