Skip to content

Instantly share code, notes, and snippets.

@JordanDelcros
Last active August 29, 2015 14:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JordanDelcros/84ef321c4a51ed6fc516 to your computer and use it in GitHub Desktop.
Save JordanDelcros/84ef321c4a51ed6fc516 to your computer and use it in GitHub Desktop.
Highlight JavaScript
// Basic JavaScript RegExps to parse JavaScript (itself ahah!)
// and translate it into HTML markup ready for CSS.
// Please, give me your feedback on twitter @JordanDelcros.
code // string (multiline) of JavaScript code
.replace(/&(lt|nbsp|amp)/gim, "&$1")
.replace(/(\/\/[^\n]*)/gi, "##comment••$1••comment##")
.replace(/(\/\*[\s\S]*?((\*\/)|$))/gi, "##comment••$1••comment##")
.replace(/(\"[\s\S]*?(\"|$))/gi, "##string••$1••string##")
.replace(/([\<\>\+\-\*\/\%\!]|\=+)/gim, "##math••$1••math##")
.replace(/(function\s*\()([^\)]+)(\s*\))/gi, "$1##parameter••$2••parameter##$3")
.replace(/([^\w])((?:(?:new|do|for|while|return|if|else|else)+\s*)+)([^\w])/gi, "$1##action••$2••action##$3")
.replace(/([^\w])(var|log|warn|info|error)([^\w])/g, "$1##object••$2••object##$3")
.replace(/([^\w])(function|window|document)([^\w])/g, "$1##primary••$2••primary##$3")
.replace(/([^\w])(this|true|false|infinity)([^\w])/g, "$1##base••$2••base##$3")
.replace(/([a-z]+\s*)\:/gi, "##property••$1••property##:")
.replace(/(?!=\#)([0-9]*\.?[0-9]+)/gi, "##number••$1••number##")
.replace(/(\t)/gim, "<span class='tabulation'>$1</span>")
.replace(/(\&\&|\|\|)/, "<span class='separator'>$1</span>")
.replace(/##comment••[\s\S]*?••comment##/gi, function( global ){
return "<span class='comment'>" + global.replace(/(##[a-z]+••)|(••[a-z]+##)/gi, "") + "</span>";
})
.replace(/##string••[\s\S]*?••string##/gi, function( global ){
return "<span class='string'>" + global.replace(/(##[a-z]+••)|(••[a-z]+##)/gi, "") + "</span>";
})
.replace(/##parameter••([\s\S]*?)••parameter##/gi, "<span class='parameter'>$1</span>")
.replace(/##action••([\s\S]*?)••action##/gi, "<span class='action'>$1</span>")
.replace(/##object••([\s\S]*?)••object##/gi, "<span class='object'>$1</span>")
.replace(/##primary••([\s\S]*?)••primary##/gi, "<span class='primary'>$1</span>")
.replace(/##base••([\s\S]*?)••base##/gi, "<span class='base'>$1</span>")
.replace(/##property••([\s\S]*?)••property##/gi, "<span class='property'>$1</span>")
.replace(/##math••([\s\S]*?)••math##/gi, "<span class='math'>$1</span>")
.replace(/##number••([\s\S]*?)••number##/gi, "<span class='number'>$1</span>");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment