在jQuery中突出显示变量和关键字

在jQuery中突出显示变量和关键字,jquery,Jquery,我试图使用jQuery突出显示代码段中的变量和关键字。假设我有这样一个java代码段 public class abc { public static void main(String args[]) { int count = 0; } } 我用“变量”按钮表示变量,用“关键字”按钮表示保留关键字。 有什么办法吗?或者我应该使用Regex吗?这里有一个解决方案,它将段落中的一些html替换为id=test /* array of words to highlight */

我试图使用jQuery突出显示代码段中的变量和关键字。假设我有这样一个java代码段

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

}
}
我用“变量”按钮表示变量,用“关键字”按钮表示保留关键字。
有什么办法吗?或者我应该使用Regex吗?

这里有一个解决方案,它将段落中的一些html替换为
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);

})
/*要突出显示的单词数组*/
var words=['dummy','surved','desktop'];
$(函数(){
/*获取包含要突出显示的单词的html*/
var wordsHtml=$('#test').html();
$.each(单词,函数(idx,单词){
var reg=新的RegExp(单词“g”);
/*将单词替换为包含单词的范围,使用css“突出显示”类*/
wordsHtml=wordsHtml.replace(reg,“+word+”);
});
/*用新的html替换旧的html*/
$('#test').html(wordsHtml);
})

演示:

您看过了吗?有一个非常非常好的(语法高亮)用Javascript编写,不难找到。哦,看看这个,搜索
语法荧光笔
,它是列表中的第一个。我使用正则表达式来实现这一点,如果你可以直接针对段落或div,看起来容易多了。我只想在学习jQuery时使用它。