There is plain text in the text_pr variable. In another variable arr are words that need to be highlighted, i.e. add a class .text_red (css-class for highlighting in red).
How to implement it?

Code = https://jsfiddle.net/tb2vv2kk/1/

 var text_pr = "Здесь простой текст со словами которые нужно подсветить, добавить класс red, Здесь простой текст со словами которые нужно подсветить, добавить класс red"; var arr = ["текст", "нужно", "red", "четыре"]; $("#button").click(function() { //$().addClass('text_red'); $('#text_rez').html(text_pr); }); 
 #button { position: relative; cursor: pointer; text-align: center; background-color: #3BA4C7; font: bold 14px Arial, Helvetica, sans-serif; margin: 10px; padding: 6px 18px; } #button:hover { color: #FFF; } .text_red { color: #F00; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <div id="button">Показать</div> <br> <div id="text_rez"></div> 

  • Read about the method indexOf() - mix
  • need to create document.createTextRange (). then findText and pasteHTML - Stack

2 answers 2

Add the following in JS

 jQuery.each(arr, function(ind, txt) { var re = new RegExp(txt,"g"); text_pr = text_pr.replace(re, '<span class="text_red">'+txt+'</span>'); }); 

before $('#text_rez').html(text_pr);

The code scrolls through the array. Using regex, find the right words and frame them in <span class="text_red"> .

However, there is one thing.
You need to change the array in the example and be careful with the class name.
There is a red element in your array that conflicts with the name of the text-red class. Those. when the queue reaches the red element in the array, it is replaced in the text, breaking the previously inserted span .

 var text_pr = "Здесь простой текст с словами которые нужно подсветить, добавить класс red, Здесь простой текст с словами которые нужно подсветить, добавить класс red"; var arr = ["текст", "нужно", "класс", "четыре"]; $("#button").click(function() { jQuery.each(arr, function(ind, txt) { var re = new RegExp(txt,"g"); text_pr = text_pr.replace(re, '<span class="text_red">'+txt+'</span>'); }); $('#text_rez').html(text_pr); }); 
 #button { position: relative; cursor: pointer; text-align: center; background-color: #3BA4C7; font: bold 14px Arial, Helvetica, sans-serif; margin: 10px; padding: 6px 18px; } #button:hover { color: #FFF; } .text_red { color: #F00; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <div id="button">Показать</div> <br> <div id="text_rez"></div> 

     for (var i = 0; i<arr.length;i++) { if(text_pr.indexOf(arr[i]) > -1){ // выставляем класс break; } } 
    • Please try to leave a little more detailed answers. - aleksandr barakin