0

I'm trying to highlight words in green for OK, yellow for Fail and red for error.

I have the result in a variable. How do I search for this words and give 3 different classes for red,green,yellow?

 //highlight words in the results
    var results = $('#results').html();
    console.log(results);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<span id="results">Fail blabla Error asda OK</span>
  • 1
    Possible duplicate of [How to highlight text using javascript](https://stackoverflow.com/questions/8644428/how-to-highlight-text-using-javascript) – Morpheus Feb 23 '18 at 16:45
  • How are you getting the data into the span out of curiosity? Is there a way to do this before javascript is necessary? – MichaelM Feb 23 '18 at 16:52

2 Answers2

2

Parse the html() and wrap substrings in span adding the appropriate class.

$("#results").html(function() {
  return $(this).html()
    .replace("Fail", '<span class="fail">Fail</span>')
    .replace("OK", '<span class="ok">OK</span>')
    .replace("Error", '<span class="error">Error</span>');
})
.fail {
  color: orange;
}

.error {
  color: red;
}

.ok {
  color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<span id="results">Fail blabla Error asda OK</span>
Takit Isy
  • 9,688
  • 3
  • 23
  • 47
void
  • 36,090
  • 8
  • 62
  • 107
0

Using replace to replace all keywords with '<span style="target_style" class="target_class">'.

//highlight words in the results
    var results = $('#results').text();
    results = results.replace(/OK/g, '<span style="background-color:green">OK</span>')
    .replace(/Fail/g, '<span style="background-color:yellow">Fail</span>')
    .replace(/Error/g, '<span style="background-color:red">Error</span>');
    $('#results').html(results);
    console.log(results);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<span id="results">Fail blaErrorbla Error a OK sda OK</span>
Sphinx
  • 10,519
  • 2
  • 27
  • 45