0

I am trying to highlight variables and keywords in a code snippet using jQuery. Suppose, I have a java snippet like this,

public class abc { 
  public static void main(String args[]) { 
    int count = 0; 

}
}

I am using button called "Variable" for variables and "Keyword" for reserved keywords. Is there any method for it? Or should I be using Regex?

unknownsatan
  • 731
  • 5
  • 16
  • 24
  • 1
    Have you looked? There is a really, really good one (syntax highlighter) written in Javascript that is not hard to find. Oh, look at that, search for `syntax highlighter` and it's the first one in the list. – Jared Farrish Jun 15 '12 at 18:15
  • I used regex for this it seems much easier if you can target the paragraph or div directly. http://stackoverflow.com/questions/119441/highlight-a-word-with-jquery – Ekim Jun 15 '12 at 18:16
  • I want to use jQuery only as I am learning it. – unknownsatan Jun 15 '12 at 18:17

1 Answers1

0

Here is a solution based on replacing some html in a paragraph with id=test

/* array of words to highlight */
var words = ['dummy', 'survived', 'desktop'];

$(function() {
    /* get html containing words to highlight*/    
    var wordsHtml = $('#test').html();
    $.each(words, function(idx, word) {
        var reg = new RegExp(word, 'g');
        /* replace word with a span containing word ,use css to "highlight" class*/
        wordsHtml = wordsHtml.replace(reg, '<span class="highlight">' + word + '</span>');
    });
    /* replace old html with new*/
    $('#test').html(wordsHtml);

})

DEMO: http://jsfiddle.net/pjBuY/

charlietfl
  • 170,828
  • 13
  • 121
  • 150