Turn specific words in array in a Tag with that word (No jQuery)

Issue

How can you make it so that with the help of a JavaScript script you can pick out a word from a text that is in a P element with a class and turn it into a tag. For example I have such a text:

<p class="codeText">Hello World, this Text say Hello World</p>

and a array in javascript:

const words = ["Hello", "World", "Text"];

How could I do that in the scheme:

If Word from Class codeText has words from the array then turn the word in <b>Word</b>

I know it’s a bit complicated, if you have any questions then please comment

Solution

Same basic concept as the one I answered a few hours ago

underline two word in a Sentence with jquery

but you want vanilla JS

Regexp

const words = ["Hello", "World", "Text"];
const codeText = document.querySelector(".codeText");
let text = codeText.textContent
words.forEach(word => text = text.replace(new RegExp(`(${word})`,"g"),"<b>$1</b>"))
codeText.innerHTML = text
<p class="codeText">Hello World, this Text say Hello World</p>

I do NOT recommend you replace the innerHTML in a loop – see the span class is mangled

const words = ["Hello", "World", "Text"];
const codeText = document.querySelector(".codeText");
words.forEach(word => codeText.innerHTML = codeText.innerHTML.replaceAll(word,`<b>${word}</b>`))
.Text { color: red; }
<p class="codeText">Hello World, this <span class="Text">Text</span> say Hello World</p>

ReplaceAll

const words = ["Hello", "World", "Text"];
const codeText = document.querySelector(".codeText");
let text = codeText.textContent;
words.forEach(word => text = text.replaceAll(word,`<b>${word}</b>`))
codeText.innerHTML = text;
.Text { color: red; }
<p class="codeText">Hello World, this <span class="Text">Text</span> say Hello World</p>

Answered By – mplungjan

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published