【问题标题】:search for text in javascript and get all its start and end index在 javascript 中搜索文本并获取其所有开始和结束索引
【发布时间】:2012-08-15 00:45:11
【问题描述】:

我有一个类似

的内容

苹果是苹果树的果仁,品种 Malus 蔷薇科(蔷薇科)的家蝇。它是应用最广泛的一种 栽培的树果,苹果是最广为人知的 众所周知,人类使用的苹果属的许多成员。 苹果长在落叶小树上。

我有一个像

这样的数组
["apple", " ", "is", " ", "the"];

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

我尝试循环内容并使用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);
}

【问题讨论】:

  • 我没有格式化您的问题,因为我不确定您所说的“内容”是什么意思。您对文本使用了h5 标签,您实际上是否在页面上有文本,或者您只是有一个字符串并尝试在此处使用h5 标签对其进行格式化?请阅读stackoverflow.com/editing-help
  • 我只有一个字符串并用 h5 格式化

标签: javascript


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

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

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

    您也可以去掉数组中的空格并将空格传递给join,以获得更小的数组。

    【讨论】:

    • 我无法加入数组和搜索,实际上我的内容可能包含不需要的空格,如 \n \r 等我也需要跳过它并搜索我使用的数组
    【解决方案3】:
    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 中的开始和结束索引列表

    【讨论】:

    • 是的,但我需要所有出现的索引
    • 好的,看看我的编辑。这是查找character 索引,而不是字符串索引。
    • 感谢 Aesthete,如果我使用 sting.search(),我会跳过像 apple is \n 这样的词,我还需要匹配具有不需要空格的同一个词
    猜你喜欢
    • 2019-07-17
    • 2018-08-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-04
    • 2011-02-18
    • 2016-11-29
    • 2020-11-19
    相关资源
    最近更新 更多