0

I'd like to dynamically check a paragraph for a list of words and then wrap those words in a span tag if found.

Example:

<p class="para">
My house is red and my front door is blue.
</p>

How could I check for the words 'house', 'red', 'door', and 'blue', as well as any others I might add to the paragraph, and then wrap them in a simple span tag which I can then style with css?

I've searched and found answers for individual words, but being a complete novice I'm not sure how to check for a list of them which I can add to.

Jerpl
  • 169
  • 1
  • 3
  • 16
  • Have you at least tried to modify one of those answers you have found to fit your needs? Any attempt of your own? – NewToJS Jul 15 '17 at 20:39

4 Answers4

1

Javascript has great regular expressions - you could use those.

    var words = ['house', 'red', 'door', 'blue'];
    // create a regular expression matching any of these words, using 'g' flag to match all instances
    var regexp = new RegExp('(' + words.join('|') + ')', 'ig');

    $('p.para').each(function(num, elem) {
        var text = $(elem).text();
        // use string.replace with $& notation to indicate whatever was matched
        text = text.replace(regexp, '<span class="$&">$&</span>');
        $(elem).html(text);
    });

This will put all your words in a span with matching name, ex <span class="house">house</span>. You could make it the same class for each one just by replacing the first '$&' with some predefined class.

arbuthnott
  • 3,819
  • 2
  • 8
  • 21
1

I gave a nice javascript-only demo, with no jQuery.

https://jsfiddle.net/66hujh1e/

(function() {
  var paragraph = document.getElementsByClassName('para')[0];
  var text = paragraph.innerHTML;

  var wordArr = text.split(' ');
  text = [];
  wordArr.forEach(function(el) {
   if(el === 'house' || el === 'red')
     el = '<span class="matched">' + el + '</span>';
    text.push(el);
  });
  console.log(text);
  text = text.join(' ');
  paragraph.innerHTML = text;
})()
.matched {
  background-color: red;
  font-weight: bold;
}
<p class="para">
My house is red and my front door is blue.
</p>

Basically, you just want to get the text, split it and process it and then put it back together, and assign it back as that nodes text. There's more elegant ways to do this with regex's and such, but basing this on low-level understanding I thought this illustrated the logic a little better.

Araymer
  • 1,315
  • 1
  • 10
  • 16
0
function wrapWithSpan(str){
    var outerDom = $('p.para');
    outerDom.html(outerDom.html().replace(RegExp(str,'ig'), '<span>' + str + '</span>'))
}

or if you have an array, you can try this

function wrapWithSpan(strArr){
    var outerDom = $('p.para');
    outerDom.html(outerDom.html().replace(RegExp(strArr.join('|'),'g'), 
    function(token){
        return '<span>' + token + '</span>';
    });
}
Koushik Chatterjee
  • 4,106
  • 3
  • 18
  • 32
0

Possible solution.

const words = ['house', 'red', 'door', 'blue'];
let elem = document.querySelector('.para');

elem.innerHTML = elem.textContent.split(' ').map(v => {
  return words.indexOf(v) > -1 ? `<span class='r'>${v}</span>` : v;
}).join(' ');
.r {
  color: blue;
}
<p class="para">
  My house is red and my front door is blue.
</p>
kind user
  • 40,029
  • 7
  • 67
  • 77