使用indexOf()获取两个索引之间的子字符串

get substring between two indexes using indexOf()

本文关键字:之间 索引 字符串 indexOf 获取 使用 两个      更新时间:2023-09-26
var myStr = "I love chocolate and strawberry, love this and that as well, and again love walking along the street";
var newStr = myStr.substr(myStr.indexOf('love'), myStr.lastIndexOf('love'));
///" chocolate and strawberry, "; //this is the output 

 var myStr = "I love chocolate and strawberry, love this and that as well, and again love walking along the street";
    
    var newStr = myStr.substr(myStr.indexOf('love'), myStr.lastIndexOf('love'));
console.log(newStr);

我如何得到第一个单词"love"和第二个单词"love"之间的文本,应该是"chocolate and strawberry"?

使用String#substringString#indexOf方法与frommindex参数

var myStr = "I love chocolate and strawberry, love this and that as well, and again love walking along the street";
var str='love', ind = myStr.indexOf(str);
var newStr = myStr.substring(ind + str.length , myStr.indexOf(str,ind + 1));
console.log(newStr);

您可以使用love拆分字符串:)并查看数组中的第二项:

var newStr = myStr.split("love")[1];

我同意上面的答案,但是如果你想知道如何获得第二个"Love"的索引,你可以在indexOf()中传递" startingposition ",所以它会在开始位置后寻找"Love"这个词

您遇到的问题是因为您发送给子字符串方法的第二个索引是最后一个单词'love'的开头,而不是它的结尾。如果你将单词"love"的长度添加到第二个索引中,你的代码应该可以正常工作。

为方便使用,将Wrap拆分为一个函数

在你的字符串上调用getTextBetween(splitOnString, middleTextDesired)

splitOnString是您要查找的文本。

middleTextDesired是您想要的中间文本的数量。1为第一,2为第二,等等…

这不是一个完整的函数,因为没有添加防御检查,但思想很清楚。

var myStr = "I love chocolate and strawberry, love this and that as well, and again love walking along the street";
    
String.prototype.getTextBetween = function(splitOn, middleTextDesired = 1) {
  return this.split(splitOn)[middleTextDesired];
}
console.log(myStr.getTextBetween('love', 1));