jQuery: syntax highlighter

I finally managed to create a jQuery syntax highlighter for the JavaScript language. This simple plugin highlights all the JavaScript keywords by replacing them with an element that will be later stylized with CSS. At the moment the default element is a simple strong tag with no classes attached to it, but you can always modify it so that it can accept a class name. Here's the code:

(function($) {


  $.fn.jsHighlight = function(options) {
  
  
    options = $.extend({
      wrapper: 'strong',
      pattern: 'break|case|catch|continue|default|do|else|finally|for|function|if|in|new|return|switch|this|throw|try|var|while'
                 
    }, options);
    
    
    return this.each(function() {
    
    
      var element = $(this);
      
      if(element[0].tagName.toLowerCase() != 'pre') {
      
      
        throw new Error('jsHighlight() needs a pre element.');
        
        return;
      
      }
      
       var content = element.html();
      
      
        
        
              
        
        var n = content.replace(new RegExp(options.pattern, 'g'), function($1) {
          return '<' + options.wrapper + '>' + $1 + '</' + options.wrapper + '>';
        });
        
       
        
        element.html(n);
      
  
    
    
    
    });  
  
  
  
  };


})(jQuery);

Because of its simplicity, this plugin works only with pre element, though you can easily remove the internal check to make it work also on other elements. A simple test:

$(document).ready(function() {

  $('pre').eq(0).jsHighlight();

});

You can make this plugin work also with the jQuery syntax by adding other patterns to the pattern option:

pattern: '..|\$|addClass|andSelf|bind|clone|...'

You can see the demo below.

Demo

Live demo

This entry was posted in by Gabriele Romanato. Bookmark the permalink.

Leave a Reply

Note: Only a member of this blog may post a comment.