如何用<span class =“x”>从数组中包装匹配的<p>字?

时间:2017-07-31 09:37:20

标签: javascript jquery arrays

我有.load(dictionary.txt)生成的任何数组vals_array现在我想比较<p>中文本换行的contenteditable div中的每个单词,如果匹配数组中的任何单词,它将把该单词包装在

以下是数组代码的文本:

var vals_array = [];

$.each(splitCntEditableTxt,function(key,val){
  var nameFound = $.inArray(val.trim().toUpperCase(), dictionary);
  if (nameFound === -1){
    //alert(val + " No Match"); //DEBUG
  } else {
    //alert(val + " found in array"); //DEBUG
    //$("#notes").append('<span class="OMG">'+val+'</span>');
    vals_array.push(val);
  }
});

这是我想用来比较过滤文本并从数组中逐个匹配的代码:

$('#notes').findText({query: vals_array}).each(function (){
  //wrap matched word with <span>
});

问题是,<p>中的文本有时会:, - - spacing,\ n \ r和其他非单词元素。那么,我如何首先过滤掉

中的文本,只留下纯文字,然后将它们与vals_array数组进行比较,如果匹配则用?包装?

非常感谢〜!!!

1 个答案:

答案 0 :(得分:0)

您可以使用String#replace替换带有链接的字词。 replace有两个参数:

  1. 要替换的正则表达式或字符串。
  2. 返回替代品的替代品或功能。
  3. 这意味着我们可以:

    1. 阅读textContent的{​​{1}},
    2. 使用<p>
    3. 匹配所有字词
    4. 对于每个单词,检查它是否在字典中,
    5. 如果是,请返回/\w+/g
    6. 如果不是,请返回
    7. 一词
    8. 将其写回<span>的{​​{1}}
    9. 以下示例显示了这些步骤。它使用了一些现代的javascript功能,因此您可能需要将其转换为es5。此外,它不能很好地处理插入位置,因此您必须fix that yourself。 (目前,它只是将其放在内容的末尾)

      示例中的<p>替换了以下字词:innerHTML<p>foo。您可以在代码段顶部的数组中添加其他字词。

      bar
      baz
      // The array source you mentioned
      const wordsToMatch = ["foo", "bar", "baz"];
      
      // For quick lookups, we make a Set
      const matchingDict = new Set(wordsToMatch);
      
      // Check if a word is in the dictionary and possibly return
      // a <span> element
      const convertWord = word => matchingDict.has(word)
        ? `<span class="highlight">${word}</span>`
        : word;
      
      // Check the textContent of an event target for words in dictionary 
      // and update accordingly
      const handleChange = e => {
        e.target.innerHTML = e.target.textContent
          .replace(/\w+/g, convertWord);
        setRangeToEnd(e.target);
      };
      
      // Attach the logic to the contenteditable <p>
      document
        .querySelector("p")
        .addEventListener("input", delay(300, handleChange));
        
        
        
      // A utility to only run our text-adaptations x ms after the last change
      function delay(dt, fn) {
        let to = null;
        
        return e => {
          clearTimeout(to);
          to = setTimeout(() => fn(e), dt);
        }
      }
      
      function setRangeToEnd(target) {
        const sel = window.getSelection();
        const range = document.createRange();
        range.selectNodeContents(target);
        range.collapse(false);
        sel.removeAllRanges();
        sel.addRange(range);
      }