如何遍历每个单词,而不仅仅是每个单词一次?

时间:2018-07-13 14:26:57

标签: javascript arrays

该函数接收文本。

当前,我传入文本,并检查单词,并告诉我是否找到每个单词的开始和结束。但是文本中有多个“ Hello”,而其他的仅指出第一个相同。如果我希望它在每场比赛中都能做到?

complexWordIdentification(text) {
  const complexWords = ['Hello', 'World', 'Complex Phrase'];
  const results = [];
  for (let i = 0; i < complexWords.length; i++) {
    // the complex word we are checking in this iteration
    const complexWord = complexWords[i];
    const match = text.search(complexWord);
    if (match !== -1) {
      // the results object
      const result = {
        begin: match,
        end: match + complexWord.length,
        text: complexWord
      };
      const index = results.length;
      results[index] = result;
      console.log(results);
    }
  }
  return results;
}
complexWordIdentification('Hello Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean mHello Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean mHello Lorem ipsum dolor sit amet, consectetuer adipiscing elit.')

当前结果:

{begin: 0, end: 5, text: "Hello"}

1 个答案:

答案 0 :(得分:3)

使用正则表达式和RegExp.prototype.exec,您可以检索匹配项的位置。

请确保使用'g'运算符定义RegExp以使其成为全局变量,以便它在第一个匹配项之后继续搜索。

function complexWordIdentification(text) {
  const complexWords = ['Hello', 'World', 'Complex Phrase'];
  const results = [];
  let match, regexp, result;

  for (let i = 0; i < complexWords.length; i++) {
    // the complex word we are checking in this iteration
    const complexWord = complexWords[i];
    regexp = new RegExp(complexWord, 'g');

    while ((match = regexp.exec(text)) !== null) {

      result = {
        begin: (regexp.lastIndex - complexWords[i].length),
        end: regexp.lastIndex,
        text: complexWord
      };
      results.push(result);
    }
  }
  return results;
}
const result = complexWordIdentification('Hello Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean mHello Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean mHello Lorem ipsum dolor sit amet, consectetuer adipiscing elit.')

console.log(result);