How to turn multiple array values into text in HTML?

76 Views Asked by At

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.

3

There are 3 best solutions below

1
Carsten Massmann On

You should probably rather use .textContent than .innerHTML, unless you really want to create a proper HTML markup text. Here is a simpler version with Array.filter() and Array.includes() that will get you the desired result:

const wordCheckOutput = document.getElementById("word-check-output"),
      wordsToCheckFor = ['the', 'a', 'ensure', 'when'],
      sampleString = 'This is a sample string to ensure the code is working.';
      
wordCheckOutput.innerText = sampleString.split(" ").filter(w=>wordsToCheckFor.includes(w)).join(", ")
<h3>The following words occur in the sentence</h3>
<div id="word-check-output"></div>

In case you want to do that with for loops then this should work:

const wordCheckOutput = document.getElementById("word-check-output"),
  wordsToCheckFor = ['the', 'a', 'ensure', 'when'],
  sampleString = 'This is a sample string to ensure the code is working.',
  results = [];

for (let arr = sampleString.split(' '), i = 0; i < wordsToCheckFor.length; i++) {
  for (let j = 0; j < arr.length; j++)
    if (wordsToCheckFor[i] === arr[j]) 
      results.push(wordsToCheckFor[i]);
}

wordCheckOutput.innerText = results.join(", ")
<h3>The following words occur in the sentence</h3>
<div id="word-check-output"></div>

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 and should therefore not be done repeatedly in a loop.

1
Ronnie Royston On

let wordsToCheckFor = ['the', 'a', 'ensure', 'when'];
let sampleString = 'This is a sample string to ensure the code is working.';

wordsToCheckFor.forEach(function(wordToCheck){
  if(sampleString.includes(wordToCheck)){
    console.log(wordToCheck + " was found.")
  }
})

0
Roko C. Buljan On

Here's an example that uses RegExp with word boundaries \b and pipe delimited | match options of the desired words to match:

const arr = ["the", "a", "ensure", "when"];
const str = "This is a sample string to ensure the code is working.";


const res = str.match(new RegExp(`\\b(${arr.join("|")})\\b`, `ig`))
document.querySelector("#word-check-output").textContent = res.join(", ");
<div id="word-check-output"></div>