Zygimantas
Zygimantas

Reputation: 563

Word highlighting in the paragraph JQuery

I wan to make a text highlighter: I have my paragraph in qtext and the words I want to highlight in the paragraph are in answerCodes. I want to add them a span class and highlight them in the paragraph. Any ideas would help!

    var answerCodes = $('[id*="_label"]').text(); 
    var qText = $('.question_text').html();
    for (var i=0; i<answerCodes.length; i++) {
        need to put something here...
    }   

Upvotes: 2

Views: 103

Answers (2)

Pranav C Balan
Pranav C Balan

Reputation: 115212

Generate regex based on the answer code and replace the html content.

// generate regex
var reg = new RegExp(
  // get all answer code elements
  $('[id*="_label"]')
  // iterate over them
  .map(function() {
    // get text content and
    // escape symbols which has special meaning in regex
    return $(this).text().replace(/[|\\{}()[\]^$+*?.]/g, '\\$&');    
  })
  // get result as array
  .get()
  // join them with pipe symbol
  .join('|'),
  // set global modifier for global match
  'g');


// iterate over p
$('.question_text').html(function(i, html) {
  // replace the question code with span wrapped content
  return html.replace(reg, '<span class="highliter">$&</span>');
});

var reg = new RegExp(
  $('[id*="_label"]').map(function() {
    return $(this).text().replace(/[|\\{}()[\]^$+*?.]/g, '\\$&');
  }).get().join('|'), 'g');


$('.question_text').html(function(i, html) {
  return html.replace(reg, '<span class="highliter">$&</span>');
});
.highliter {
  color: red
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label id="_label1">abc</label>
<label id="_label1">test</label>

<div class="question_text">a a a a abc bb b test dd abc fff</div>

Upvotes: 1

David Lee
David Lee

Reputation: 1

use RegExp to replace.

for (var i=0; i< answerCodes.length; i++) {
    qText = qText.replace(new RegExp(answerCodes[0], 'g'), '<span class="highlight">$1</span>');
}

Upvotes: 0

Related Questions