skip to Main Content

I’m trying to wrap specific words ("Ethan", "passionate", "UX/UI", and "Designer") in a span class in a paragraph for individual styling. However, since "Ethan" is followed directly by a comma in the HTML, the JavaScript only selects it if I include the comma ("Ethan,")—resulting in the comma being styled as well, which I don’t want. How can I apply the style only to "Ethan" without affecting the comma?

Here’s my current JS:

document.addEventListener('DOMContentLoaded', function() {
  const herotext = document.getElementById('herotext');
  const words = herotext.innerText.split(' ');
    
  herotext.innerHTML = words.map(word => {
    if (['Ethan', 'passionate', 'UX/UI', 'Designer'].includes(word))
    {
      return `<span style="color: #F33;">${word}</span>`;
    } else {
      return `<span>${word}</span>`;
    }
  });
});        

And the HTML:

<h1 id="herotext">Hi, I’m Ethan, a passionate UX/UI Designer from the scenic landscapes of Northern Ireland.</h1>

Thanks!

I’ve already tried wrapping the word "Ethan" in a <span> element and applying a specific CSS style to it, but this didn’t work. The issue is that in the HTML, "Ethan," appears as a single entity (with the comma directly after the name), preventing the span from targeting just "Ethan."

Here’s the HTML I used:

<h1 id="herotext">Hi, I’m <span class="highlight">Ethan</span>, a passionate UX/UI Designer from the scenic landscapes of Northern Ireland.</h1>

And the CSS:

.highlight {
    color: #333;
}

I know this is a very specific use case, but this is the only sentence I want to apply this algorithm to. Setting some rules around excluding commas from the styling seems like it would resolve the issue, I’m just not sure how to do this as I’m not a developer and have very very basic development knowledge – some help/a solution would be massively appreciated!

3

Answers


  1. In your map, you can use replace() to clean up the words, as follows.

    And if you want to have space between your words, instead of commas, you can use .join(' ') on the array

    document.addEventListener('DOMContentLoaded', function() {
      const herotext = document.getElementById('herotext');
      const words = herotext.innerText.split(' ');
        
      herotext.innerHTML = words.map(word => {
        const clean_word = word.replace(",","")
        if (['Ethan', 'passionate', 'UX/UI', 'Designer'].includes(clean_word))
        {
          return `<span style="color: #F33;">${clean_word}</span>,`;
        } else {
          return `<span>${word}</span>`;
        }
      });
    });
    .highlight {
        color: #333;
    }
    <h1 id="herotext">Hi, I’m <span class="highlight">Ethan</span>, a passionate UX/UI Designer from the scenic landscapes of Northern Ireland.</h1>
    Login or Signup to reply.
  2. you can apply the span styling to the specific words without affecting punctuation like THIS

    const wordsToHighlight = ["Ethan", "passionate", "UX/UI", "Designer"];
            const heading = document.getElementById("herotext");
            
            function highlightWords(element, words) {
                let html = element.innerHTML;
            
                words.forEach(word => {
                    
                    const regex = new RegExp(`\b(${word})\b`, 'g');
                    html = html.replace(regex, `<span class="highlight">$1</span>`);
                });
            
                element.innerHTML = html;
            }
            
            
            highlightWords(heading, wordsToHighlight);
    .highlight{
    color:blue;
    }
     <h1 id="herotext">Hi, I&#8217;m Ethan, a passionate UX/UI Designer from the scenic landscapes of Northern Ireland.</h1>
    Login or Signup to reply.
  3. You can split by the keywords, followed by space or comma (look-ahead regex of (?=[, ]), the regex being new RegExp(word + "(?=[, ])", 'g')) and join back by word being inserted into the template of your preference, looping the keyword array in the process.

    document.addEventListener('DOMContentLoaded', function() {
      const herotext = document.getElementById('herotext');
      const keywords = ['Ethan', 'passionate', 'UX/UI', 'Designer'];
      let temp = herotext.innerText;
      for (let word of keywords) {
          temp = temp.split(new RegExp(word + "(?=[, ])", 'g')).join(`<span style="color: #F33;">${word}</span>`)
      }
      herotext.innerHTML = temp;
      
        
    });
    .highlight {
        color: #333;
    }
    <h1 id="herotext">Hi, I&#8217;m Ethan, a passionate UX/UI Designer from the scenic landscapes of Northern Ireland.</h1>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search