I am quite new to JavaScript and am trying to create a tool that will check for certain words within given text. Right now I am testing and can have the results logged in the console but am having trouble getting all of the results to display using innerText. Basically, I’m wanting it to show which of the given words exist within the string, but it will only show one of the results.
Here is my JS code:
const wordCheckOutput = document.getElementById("word-check-output");
let wordsToCheckFor = ['the', 'a', 'ensure', 'when'];
let sampleString = 'This is a sample string to ensure the code is working.'
function wordCheck() {
let i = [];
for (let i = 0; i < wordsToCheckFor.length; i++) {
for (let j = 0; j < sampleString.split(' ')[j]; j++)
if (wordsToCheckFor[i] === sampleString.split(' ')[j] {
let results = wordsToCheckFor[i];
console.log(results);
wordCheckOutput.innerText = results;
}
}
}
I’m fairly certain I have to change the results with the [i], but everything I’ve tried hasn’t worked and I’m sure I’m missing something.
2
Answers
You should probably rather use
.textContent
than.innerHTML
, unless you really want to create a proper HTML markup text. Here is a simpler version withArray.filter()
andArray.includes()
that will get you the desired result:In case you want to do that with
for
loops then this should work:Please note, that I split the text array only once, before I go into the
for
loop. I also do the assignment to the.innerText
property of the results div outside the loop. Assigning new text to.ìnnerHTML
,.ìnnerText
or.textContent
properties of a DOM elements will slow down the overall page rendering process.