在javascript中搜索文本并获取其所有开始和结束索引

时间:2012-08-14 10:55:38

标签: javascript

我有像

这样的内容
  

苹果是苹果树,马鲁斯种的果实   家蝇在玫瑰科(蔷薇科)。它是最广泛的之一   栽培的树果,苹果是最好的和最广泛的   已知人类使用的许多马鲁斯属成员。   苹果在小落叶树上生长。

我有一个类似

的数组
["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);
}

3 个答案:

答案 0 :(得分: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;
    }
}

小提琴here

答案 1 :(得分:0)

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

arr

您也可以摆脱数组中的空格,并将空格传递给var start = str.indexOf(arr.join("")); ,而不是更小的数组。

答案 2 :(得分: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的列表
相关问题