How to create and use a Syntax Highlighter with JavaScript?

JavascriptWeb DevelopmentObject Oriented Programming

To create and use syntax highligher, the code is as follows −


 Live Demo

<!DOCTYPE html>
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   .colorLinks {
      color: rgb(131, 44, 212);
      text-decoration: none;
      font-size: 20px;
      font-weight: bold;
   .setColor {
      margin: 20px;
      padding: 10px;
      border: none;
      font-size: 18px;
      background-color: rgb(226, 43, 89);
      color: white;
<h1>Syntax Highlighting example</h1>
<div class="CodeDiv">
<a href="">Go to</a>
<a href="">Go to</a>
<button class="setColor" onclick="highlightLinks()">Click Here</button>
<h2>Click the above button to highlight the links</h2>
   var anchrorRg = /[^<]*(<a href="([^"]+)">([^<]+)<\/a>)/g;
   function highlightLinks() {
      var text = document.querySelector(".CodeDiv").innerHTML;
      text = text.replace(anchrorRg, function() {
         function check(arguments) {
            let tempArr = [];
            tempArr.push(, 2, 4));
            return `<a class="colorLinks" href=${tempArr[0][0]}>${tempArr[0][1]}</a><br>`;
         return check(arguments);
      document.querySelector(".CodeDiv").innerHTML = text;


The above code will produce the following output on window size greater than 700px −

On clicking the “Click Here” button −

Updated on 12-May-2020 12:23:53