1

假设我有一个长字符串,例如:

var sentence = "Marry had a little lamb, Peter had a little wolf, the wolf ate the little lamb and the little wolf was happy.";

我需要在字符串中找到子字符串“Peter”的位置。

那当然是var pos = sentence.indexOf("Peter");

但是现在我有一个问题 - 我需要找到子字符串“lamb”的最后一次出现和子字符串“wolf”before pos的第一次出现 pos

我怎么做?请纯 Javascript,不要 jQuery。

4

2 回答 2

4

怎么样:

var pos = sentence.indexOf("Peter");
var pos2 = sentence.lastIndexOf("lamb", pos);
var pos3 = sentence.indexOf("wolf", pos);

示例:http: //jsfiddle.net/ZqsfZ/

这里的关键是 的fromIndex参数lastIndexOf。它允许您从指定的索引中搜索字符串(向后)以查找第一次出现的单词。

请参阅 和 的lastIndexOf文档indexOf

于 2012-05-28T17:45:50.843 回答
1
var sentence = "Marry had a little lamb, Peter had a little wolf, the wolf at the little lamb and the little wolf was happy.";
var pos = sentence.indexOf("Peter");
var last_lamb = sentence.substr(0,pos).lastIndexOf("lamb");
var first_wolf = sentence.indexOf("Peter", pos);
于 2012-05-28T17:44:06.983 回答