将每个单词放入<a> tag and highlighting the begin to end of each word

时间:2018-07-16 09:23:05

标签: javascript html css

Each word has a begin, end, and returns the word too as text. I need to put each word into an <a> tag and also highlight each word.

complexWordIdentification(text, words) {
  // list of "complex words"
  const complexWords = words;
  // array will be populated with results.
  const results = [];
  // loop through each complex word and see if it occurs in the text
  let match, regexp;

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

    while ((match = regexp.exec(text)) !== null) {
      // the results object
      const result = {
        begin: (regexp.lastIndex - complexWords[i].length),
        end: regexp.lastIndex,
        text: complexWord
      };
      // add the object to the results array
      const index = results.length;
      results[index] = result;
      console.log(results[index]);
    }
  }
  // return the results array when done
  return results;
}

The results to this function would be this:

{begin: 6, end: 11, text: "Lorem"}
{begin: 112, end: 117, text: "Lorem"}
{begin: 218, end: 223, text: "Lorem"}

I have a function which I can put words into an <a> tag and highlight them this is the function:

highlightSelection() {
  this.complexWordIdentification(this.postIWant, this.theHardWords);
  const userSelection = window.getSelection();
  if (userSelection.toString() === null) {
    return;
  } else {
    for (let i = 0; i < userSelection.rangeCount; i++) {
      this.highlightRange(userSelection.getRangeAt(i));
      this.word = userSelection.toString();
    }
  }
}

guidGenerator() {
  const S4 = () => {
    return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
  };
  return (S4() + S4() + '-' + S4() + '-' + S4() + '-' + S4() + '-' + S4() + S4() + S4());
}

highlightRange(range) {
  const newNode = document.createElement('a');
  newNode.id = this.guidGenerator();
  newNode.className = 'annotation_class';
  newNode.setAttribute(
      'style',
      'background-color: yellow; display: inline;'
    ),
    range.surroundContents(newNode);
  this.viewAnnotation(newNode.id);
}

That function above can highlight text etc and do what I want to do but that would be manual, I need to do it when I run the complexWordIdentification function to put each word into an <a> tag and highlight them.

Anyone got any advice on how to get around this, many thanks in advance!

2 个答案:

答案 0 :(得分:0)

我可能会缺少一些要求,但是如果我不需要所有单词索引的列表,我只会选择基本的String.replace()

const guid = () => {
  const S4 = () => {
    return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
  };
  return (S4() + S4() + '-' + S4() + '-' + S4() + '-' + S4() + '-' + S4() + S4() + S4());
};
const words = [
  "Lorem",
  "ipsum",
  "foo",
  "bar",
  "baz"
];
const highlight = ( node, words ) => {
  const text = node.innerHTML;
  const highlighted_text = words.reduce(( text, word ) => {
    return text.replace( new RegExp( word, 'g' ), `<a id="${guid()}" class="highlighted">${word}</a>` );
  }, text );
  node.innerHTML = highlighted_text;
};

highlight( document.querySelector( '#text_snippet' ), words );
.highlighted {
  background-color: steelblue;
  color: white;
}
<div id="text_snippet">Lorem ipsum dolor sit amet, pri posse veniam eu. Adhuc appareat argumentum has cu. Vim cu tale moderatius. Eos cu nostrud vocibus offendit.</div>

答案 1 :(得分:0)

这是解决我遇到的问题的有效方法。

有了这个词,我可以将其自动放入<a>中并突出显示。

getWords(words) {
    this.highlight(words);
}

highlight = (words) => {
    const high = document.getElementById('scrollable');
    const paragraph = high.innerHTML.split(' ');
    const res = [];

    paragraph.map(word => {
      let t = word;
      if (words.indexOf(word) > -1) {
        t = '<a class="clickable" style="background-color: yellow;">' + word + '</a>';
      }
      res.push(t);
    });
    high.innerHTML = res.join(' ');
}