3

I guess I'm too dumb for this. Why my code only replace the first instance of each word? I want to highlight all words with those names

//highlight words in the results
$("#results").html(function() {
  return $(this).html()
    .replace("OK", '<span class="label label-success p-3">OK</span>')
    .replace("ERROR:", '<span class="label label-danger p-3">ERROR:</span>')
    .replace("FAIL:", '<span class="label label-warning p-3">FAIL:</span>')
    .replace("AssertionError:", '<span class="label label-warning p-3">AssertionError:</span>');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

<span id="results" style="white-space: pre-line">Running test: fasf
.
----------------------------------------------------------------------
Ran 1 test in 0.652s

OK
FAIL:
ERROR:
Running test: test1
.
----------------------------------------------------------------------
Ran 1 test in 15.457s

OK
FAIL:
ERROR:
</span>
phuzi
  • 12,078
  • 3
  • 26
  • 50
  • 2
    Possible duplicate of [jQuery replace all occurrences of a string in an html page](https://stackoverflow.com/questions/25109275/jquery-replace-all-occurrences-of-a-string-in-an-html-page) – Banana Mar 13 '18 at 11:57

2 Answers2

2

You'll have to use a regular expression with the 'g' flag if you want to replace all.

See this little snippet:

const theString = 'foo';

console.log(theString.replace('o', 'i'))
console.log(theString.replace(/o/g, 'i'))

see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace

ben
  • 3,558
  • 1
  • 15
  • 28
2

Use Regex, "OK" to /OK/g with global flag.

//highlight words in the results
    $("#results").html(function() {
        return $(this).html()
            .replace(/OK/g, '<span class="label label-success p-3">OK</span>')
            .replace(/ERROR/g, '<span class="label label-danger p-3">ERROR:</span>')
            .replace(/FAIL/g, '<span class="label label-warning p-3">FAIL:</span>')
            .replace(/AssertionError/g, '<span class="label label-warning p-3">AssertionError:</span>');
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">


<span id="results" style="white-space: pre-line">Running test: fasf
.
----------------------------------------------------------------------
Ran 1 test in 0.652s

OK
FAIL:
ERROR:
Running test: test1
.
----------------------------------------------------------------------
Ran 1 test in 15.457s

OK
FAIL:
ERROR:
</span>
Pedram
  • 15,766
  • 10
  • 44
  • 73