Search code examples
javascriptjquerycontainskeyword

If element contains any of these words then wrap that word in span


I'd like to highlight certain words if they're found within a title by wrapping those words in a span class. Is there a way of writing a list of words to check for and then using the same command to wrap any of those words with the span class?

For example:

<h1>This title contains the word Balloon</h1>
<h1>This title contains the word Oranges</h1>
<h1>This title doesn't contain either of those terms</h1>

Something to check each of those three elements (but there would be 20 or so) for the words Balloon or Oranges and then wrap just those words in a span color.

I could use:

$('h1').html($('h1').html().replace(/(balloon)/g,'<span class="red">balloon</span>'));

but I'd have to write that query for every word, whereas I'd like something a little simpler, if possible.


Solution

  • You can keep an array of words, then iterate and replace the words in each header

    var words = [
        "balloon",
        "either"
    ];
    
    $('h1').html(function(_,html) {
        var reg = new RegExp('('+words.join('|')+')','gi');
        return html.replace(reg, '<span class="red">$1</span>', html)
    });
    .red {color : red}
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    
    <h1>This title contains the word Balloon</h1>
    <h1>This title contains the word Oranges</h1>
    <h1>This title doesn't contain either of those terms</h1>