title: JavaScript: How to flag words in a string to be shown in a different colour where each char of the string is appended to an element one by one?
body: <p>I'm writing a function that takes in a string (e.g. "Hello World!") and appends each character of the string to an HTML element with a delay in between each character (i.e. creating a type writer effect). </p>
  
  <p>I want to flag certain words in the string and colour it (e.g. "Hello") so that each character printed is coloured. </p>
  
  <p>I've seen other examples of this but all of them have the string hardcoded or do not allow the colouring of certain words.</p>
  
  <p>I've tried inserting characters (e.g. ☺) into the string as a flag and when I encounter these, I colour every letter until I encounter it again.</p>
  
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>// start with this string
  let originalStr = "Hello Wor☺ld";
  
  // insert "☺" at the start and end of "Wor☺ld"
  let str = "Hello ☺Wor☺ld☺!";
  let isFlagged = false;
  str = str.split("");
  
  str.forEach(function(item){
      if (item ==="☺" &amp;&amp; !isFlagged){
          isFlagged = true;
      }else if (item === "☺" &amp;&amp; isFlagged){
          isFlagged = false;
      }else if (isFlagged){
          console.log(item + " red");
      }else{
          console.log(item);
      }
  });</code></pre>
  </div>
  </div>
  </p>
  
  <p>Desired output is each char of "Wor☺ld" is logged with " red" appended to it. 
  Here, "Wor" is correctly flagged, but "☺ld" is not.</p>
  
  <p>This works fine but breaks if "☺" already existed within the string and I'm wondering if there's a better way to handle the flagging of words.</p>