I've created a JavaScript application to highlight the syntax of HTML and PHP. I know a lot of syntax highlighter are available nowadays, I just created to extend my knowledge in JS and regular expressions. I only wanted to know if its the right way to do this. (The code below works fine.)
js/codeHighlighter.js
function codeHighlighter(){
var obj=document.getElementsByTagName("code");
for(var i=0;i<obj.length;i++){
var data=obj[i].innerHTML;
data=data.replace(/<(.*?)>/g,"<span class='html-tag'><$1></span>");
data=data.replace(/"(.*?)"/g,"<span class='string-value'>"$1"</span>");
data=data.replace(/<\?(.*?)\s/g,"<span class='php-tag'><?$1</span>");
data=data.replace(/\s\?>/g,"<span class='php-tag'>?></span>");
data=data.replace(/\/\* (.*?) \*\//g,"<span class='comment'>/* $1 */</span>");
data=data.replace(/(new|echo|print|while|for|foreach|class|public|function|static|protected|private|return|required|required_once|include|include_once)[^=]/g,"<span class='reserved'> $1 </span>");
data=data.replace(/\\n/g,"<br/>");
data=data.replace(/\\t/g,"  ");
obj[i].innerHTML=data;
}
}
index.html
<html>
<head>
<title>Code Highlighter</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="js/codeHighlighter.js" type="text/javascript"></script>
<script>
window.addEventListener("load", codeHighlighter);
</script>
<style>
code{
font-family: arial;
}
.html-tag{
color:#090;
}
.string-value{
color:#900;
}
.reserved{
color:#009;
}
.php-tag{
color:#f00;
}
.comment{
color:#444;
}
</style>
</head>
<body>
<div>This application highlights `php` and `html` code.</div>
<code>
/* A sample code. */\n
<div class="code" >\n
\t Hello!\n
</div>\n
<?php\n
class Anish(){\n
\n
\t public function __construct(){\n
\t\t return "Hello";\n
\t }\n
\n
}\n
$anish=new Anish();\n
echo $anish;\n
?>\n
</code>
</body>
</html>