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 …
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>