0

我收到一个有很多键的对象,其中两个是“title”和“body”,我还有一个包含一些关键字的数组。我需要在 object.body 中匹配这些数组关键字以以某种方式突出显示它们,一种选择可能是将这些匹配的单词包装在<pre class="highlight"> Matched word inside Object.body </pre>标签中。

我宁愿使用原始 JavaScript 来实现这一点。

我试过了:

function (data) {

        // parseKeys() returns an array with the words to find inside object.body
        var key_words = this.parseKeys();
 
// data is the object within I have to find inside key:body the array strings
        for (var i = 0; i < data.length; i++) {
          if (data[i].body.includes(key)){
            console.log("****");
          }
        }
      }
4

1 回答 1

0

const keywords = ["doing", "only", "twice"];

const testObj = {
  title: "Whatever1",
  body: "Doing this only once or twice"
}

const checkBodyText = (obj) => {
  const bodyWords = obj.body.split(' ').map(el => el.toLowerCase());
  const matchingWords = bodyWords.filter(el => keywords.includes(el));
  const matchedWordsContainer = document.getElementsByClassName('highlight')[0];
  matchedWordsContainer.innerText = matchingWords.join(' ');
}

checkBodyText(testObj);
.highlight {
  color: red;
}
<pre class="highlight"></pre>

您可以创建一个变量来保留关键字。我刚刚创建了一个虚拟对象,并将“ object.body”中的每个单词与列表中的任何关键字进行比较,匹配的关键字只是简单地显示。Ofc 这种方法还会有一些其他的边缘场景,例如主体句中的标点符号。

于 2020-01-14T13:22:29.957 回答