Highlighter //JavaScript Repository

Description

Looks for occurrences of one or more strings on the text and calls a callback to replace it.
Created: 2006.01.13

Code (Download)

//+ Carlos R. L. Rodrigues
//@ http://jsfromhell.com/string/highlight [rev. #1]

String.prototype.highlight = function(f, c, i){
    var r = this, t = /([(){}|*+?.,^$\[\]\\])/g, i = !i ? "i" : "", rf = function(t, i){
        return r.lastIndexOf("<", i) > r.lastIndexOf(">", i) ? t : c(t, p);
    };
    for(var p = -1, l = (f = f instanceof Array ? f : [f]).length; ++p < l;)
        r = r.replace(new RegExp(f[p].replace(t, "\\\$1"), "gm" + i), rf);
    return r;
}

Example (Example)

<style type="text/css">
body{
    margin: 3px;
}
.bg0{
    color: #fff;
    font: bold 30px verdana;
    border: 1px solid #000;
    background: #f00;
}
.bg1{
    color: #0f0;
    background: #000;
    font-weight: bold;
}
.bg2{
    color: #00F;
    background: #FF0;
    font-weight: bold;
}
.bg3{
    color: #000;
    background: #eee;
    font-weight: bold;
}
</style>
<script type="text/javascript">
function c(s, i){
    return '<span class="bg' + i + '">' + s + '</span>';
}
var s = 'blabla <a href="http://jsfromhell.com">JSFromHell</a>';
document.write(s.highlight(["JS", "from", "o", "l"], c));
</script>

Help

String.highlight(words: Array, replaceCallback: Function(s: String, i: Integer): string, [caseSensitive: Boolean = false]): String
Looks for ocurrences of one or more strings inside the text and calls a callback to replace it. The function doesn't search inside html tags.
words
words to be searched
replaceCallback
function that will be called for each match, receives as first argument the searched word, the second one is the index of it on the array that was setted on the "words" argument and it must return a string that will replace the matched one.
caseSensitive
indicates if the search should be case-sensitive

Rank (Votes: 13)

3.92