We Recommend

Pro JavaScript Techniques Pro JavaScript Techniques
Pro JavaScript Techniques is the ultimate JavaScript book for the modern web developer. It provides everything you need to know about modern JavaScript, and shows what JavaScript can do for your web sites. This book doesn't waste any time looking at things you already know, like basic syntax and structures.


Posted By

Leech on 07/21/06


Tagged

search String text highlight


Versions (?)


Who likes this?

9 people have marked this snippet as a favorite

Roshambo
mate
jkochis
visualAesthetic
shachi
neuroasis
vali29
buscarini
hans


Highlighter v1.0


Published in: JavaScript 


URL: http://jsfromhell.com/string/highlight

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

  1. /*
  2. **************************************
  3. * String.highlight v1.0 *
  4. * Autor: Carlos R. L. Rodrigues *
  5. **************************************
  6. */
  7. String.prototype.highlight = function(f, c, i){
  8. var r = this, t = /([(){}|*+?.,^$\[\]\\])/g, i = !i ? "i" : "", rf = function(t, i){
  9. return r.lastIndexOf("<", i) > r.lastIndexOf(">", i) ? t : c(t, p);
  10. };
  11. for(var p = -1, l = (f = f instanceof Array ? f : [f]).length; ++p < l;)
  12. r = r.replace(new RegExp(f[p].replace(t, "\\\$1"), "gm" + i), rf);
  13. return r;
  14. }

Report this snippet 

You need to login to post a comment.