Build Online Code Formatter

Before we jump into this topic, I would like to recommend you to go through the "Building a Code Editor with CodeMirror" topic. This is a continuation of the previous topic.

In previous topic we have learned following things:

  • How to use a code mirror in order to build a web based code editor?
  • Learned about syntax highlighter extension for code mirror.
  • Learned about theme extension for code mirror.
Now we will be using a code beautifier on top of the code mirror in order to build Code Formatter online tool. Below pic depicts what we are trying to achieve.

Brighten Minds Build Online Code Formatter

Steps to implement it

  • First list down list of libraries required to achieve it.
    • Bootstrap 5 CSS: For UI rendering. This is optional.
    • JQuery: Will use to assign some default value for Editor 1. And later to add a click event listener on "Format" button.
    • Code Mirror for Editor 1 and Editor 2. [css, js, language mode(syntax highlighter) and theme.]
    • js-beautify: For formatting code which we will write inside Editor 1.
  • Next we will build both code editor. Please follow the previous topic.
  • Next add "Format" button below the code editor.
  • Now we will add a click event on the "Format" button to perform actual formating of written code and then assign formatted value to Editor 2.
    After you embed the js-beautify <script> tags in your html file, it will expose three functions: js_beautify, css_beautify, and html_beautify. In the current example we will use the js_beautify function to format javascript code.
  • 	const options = { indent_size: 2, space_in_empty_paren: true };
          $('.btn').click(function() {
            const newval = js_beautify(editor1.getDoc().getValue(), options);
Below is a live example
Brighten Minds Build Online Code Formatter

Complete Code

    <link href='' rel='stylesheet' type='text/css'/>
    <link rel="stylesheet"
    <link rel="stylesheet"
    <script src="" type="text/javascript"></script>
    <script type="text/javascript"
    <script type="text/javascript"

    <script type="text/javascript"

Code Repo