Highlighter v1.0 //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 )

/*
**************************************
* String.highlight v1.0              *
* Autor: Carlos R. L. Rodrigues      *
**************************************
*/
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 ( See 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 (8 votes)

4.88
0 1 2 3 4 5