Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to highlight specific words from an array within a paragraph?

Within a paragraph I want to highlight all words that are present within an array like …

var highlightword  = ["This", "field","need ", "examples","may"];

How would one approach a solution. The problem specific code I came up with so far does access the paragraph’s text-content, splits the string at every whitespace-sequence and wraps each word into a -tag. How does one achieve the highlighting of the array specific words?

This is what I came up with so far …

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

const words = $("p").text().split(/\s+/);
const text = words.join("</span> <span>");

let incorrectWord = null;

$("p")
  .first()
  .html("<span> " + text + "</span>");
 p span {
  background-color: #fc0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<blockquote id="a1" contenteditable="true">
  <p>
    This domain is established to be used for illustrative examples in documents. You may use this domain in examples
    without prior coordination or asking for permission.
  </p>
</blockquote>

>Solution :

You can use reduce instead of join:

const highlightword  = ["This", "field","need ", "examples","may"];
const words = $("p").text().split(/\s+/);

const result = words.reduce((accumulator, currentValue)=>{
    if (highlightword.includes(currentValue))
        return `${accumulator}<span>${currentValue}</span>`;
    else
        return `${accumulator} ${currentValue} `;
    }, "");

$("p")
  .first()
  .html(result);
p span {
  background-color: #fc0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<blockquote id="a1" contenteditable="true">
  <p>
    This domain is established to be used for illustrative examples in documents. You may use this domain in examples
    without prior coordination or asking for permission.
  </p>
</blockquote>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading