最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Return only text before last underscore in JavaScript string - Stack Overflow

programmeradmin4浏览0评论

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'

Share Improve this question asked Jul 5, 2016 at 16:13 Valor_Valor_ 3,5919 gold badges63 silver badges116 bronze badges 1
  • You can use a RegExp "Arthropoda_Arachnida_Zodariidae_Habronestes_hunti".replace(/(.*)_.*$/g, "$1") – user6445533 Commented Jul 5, 2016 at 16:26
Add a ment  | 

4 Answers 4

Reset to default 11

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"

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) 
发布评论

评论列表(0)

  1. 暂无评论