Search code examples
javascripttextcolors

Change color of specific words or letter combinations


I need to change the color of certain letter combinations in an element with a class. For example: <span class="title">ACPRO2000</span> - in this I would want 'ACPRO' to be orange and the rest to stay the default color.

I should note that I am not adept at javascript at all.


Solution

  • Functional approach with vanilla javascript

    const highlightText = (text, elem, color) => {
       const element = document.querySelector( elem );
             element.innerHTML = element.innerHTML.replaceAll( text, `<span style="color: ${color}">${text}</span>`);
    }
    
    
    highlightText("ABC", '#lettersList', 'orange')
    highlightText("0", '#lettersList', 'red')
    
    highlightText("World", '#myDiv2', 'green')
    <div id="lettersList">ABC2012</div>
    
    <div id="myDiv2">Hello World</div>