Code highlighting on the site using Js and Css

While maintaining my site, describing lines of code, I began to notice that for better readability, minimal highlighting is needed. After some googling, I came across dozens of solutions based on different frameworks. I did not burn with the desire to deal with this trifle a lot (after all, laziness is the engine of progress). I came across the easiest way to implement such an implementation using Js and Css. Real source here .

Since I have jQuery included on my site, I took this Js code :

(function($){

$.fn.syntax = function(){
return this.each(function(){
var jqCode = $(this);
var code = jqCode.html();
code = code
.replace(/(var|function|typeof|new|return|if|for|in|while|break|do|continue|case|switch)([^a-z0-9\$_])/g,'<span class="kwrd-code">$1</span>$2')
.replace(/(\{|\}|\]|\[|\|)/gi,'<span class="kwrd-code">$1</span>')
.replace(/(\/\/[^\n\r]*(\n|\r\n))/g,'<span class="comm-code">$1</span>')
.replace(/('.*?')/g,'<span class="str-code">$1</span>')
.replace(/([az\_\$][a-z0-9_]*)\(/gi,'<span class="func-code">$1</span>(')
.replace(/\t/g,' ');
jqCode.html(code);
});
}

})(jQuery);

$('code.code').syntax();

You can understand that replace , according to the rules, the expressions we need, quotes and just rules on span with certain classes.

For this code to work, paste it into a js file and connect it to your site.

The line $('code.code').syntax() - runs the code for the code tag that has the code class. <code class='code'></code> .

And here is the syntax :

.str-code{color:red}/* Strings are red */
.func-code{color:blue}/* User functions are blue */
.comm-code{color:orange}/* Comments are orange */
.kwrd-code{font-weight:bold}/* Keywords are bold */
.str-code span{color: red;font-weight:normal}/* Everything inside the string — line */
.comm-code span{color:orange;font-weight:normal}/* Everything inside the — comment */

Similarly, you should create a css file and include it on the page where the top js script is used. Since all the spans it creates are styled exactly by these rules.

1177 0

Comments

Be the first to review this item. Share your rating and review so that other customers can decide if this is the right item for them.
You have to log in to leave a comment. Sign in

Similar articles