0

我有一个内容

苹果是玫瑰科(蔷薇科)苹果树的果仁。它是最广泛种植的树果之一,苹果是人类使用的许多苹果属成员中最广为人知的。苹果长在落叶小树上。

我有一个像

["apple", " ", "is", " ", "the"];

使用这个数组如何在javascript中找到单词apple的开始索引和结束索引?

我尝试循环内容并使用indexOf但我无法获得单词的所有索引

这是我试过的

var matchs =[];
var content = "a b c defgh a b csdwda abcdfd";
var arrayWord =["a"," ", "b"];
var w =0;
var pos =0;
var firstIndex = content.indexOf(arrayWord[w],pos);
pos = firstIndex;
while (pos > -1) {
    pos+=arrayWord[w].length;
    w++; 
    pos = content.indexOf(arrayWord[w], pos);
    matchs.push(firstIndex,pos);
}
4

3 回答 3

1

阅读您的评论后,我认为这就是您所追求的。如有必要,您可以添加更多替换语句。

var text,
    pos,
    start,
    matches = [],
    charArr,
    charText,
    currentMatch;

text = $("h5").text( );

//white spaces must match length of string being replaced
text = text.replace("\r\n","    ");
charText = text.split("");

charArr = ["apple", " ", "is", " ", "the"].join("").split("");
currentMatch = 0;

// Loop through char array ignoring multiple white spaces
for( pos = 0; pos < text.length; pos += 1 ) {

    if( currentMatch === 0 ) start = pos;

    if( charText[pos] === charArr[currentMatch] ) {
        currentMatch += 1;      
    } else if( charText[pos] !== " " ) {
        currentMatch = 0;
    }

    // matched entire array so push to matches
    if( currentMatch === charArr.length ) {     
        matches.push( [ start, pos] );
        currentMatch = 0;
    }
}

在这里提琴

于 2012-08-14T16:45:11.907 回答
0

假设我已经正确理解了您的问题,您可以join使用数组并使用indexOf字符串的方法来获取起始索引(此示例假设您的字符串存储在其中,str并且您的数组存储在 中arr):

var start = str.indexOf(arr.join(""));

您也可以摆脱数组中的空格并将空间传递join给更小的数组。

于 2012-08-14T10:59:18.830 回答
0
var text = $("h5").text(); // Get the text from your h5.
var searchText = "apple is the";
var found = []
function findAll(string) {
  var startIdx = string.search(searchText);
  var endIdx = startIdx + searchText.length;
  if(startIdx == -1) {
    return;
  }
  else {
    found.append([startIdx, endIdx]);
    findAll(string.substring(endIdx, string.length));
  }
}
findAll(text);

这将递归搜索字符串,直到searchText找到所有实例。

每次出现都存储为开始和结束索引的[[start, end],[start,end],...]列表found

于 2012-08-14T11:03:26.893 回答