Search code examples
javascriptformattinggoogle-chrome-devtoolsfirebugconsole.log

How to format the function body when using toString()


Let's say I have this function from a minified JavaScript file:

function fn(){console.log('Lorem');console.log('Ipsum');}

I would like to get a pretty print, indented version when calling:

console.log(fn.toString());

Expected output :

function fn() {
    console.log('Lorem');
    console.log('Ipsum');
}

Instead of:

function fn(){console.log('Lorem');console.log('Ipsum');}

Anyway to do that?


Solution

  • JavaScript does not have a built-in function to do this. So, if you want to do pretty printing programmatically, you'll have to do it manually. To get the function´s source, there is a non-standard Function.prototype.toSource() function, which is only supported by Firefox, though. A very simple pretty-print function covering your example is:

    function prettyPrint(source) {
      let formattedSource = fn.toSource ? fn.toSource() : "";
    
      // Add line breaks after curly braces and semicolons
      formattedSource = formattedSource.replace(/([{};])/g, "$1\n");
    
      // Add space after opening curly brace
      formattedSource = formattedSource.replace(/(\S)\{/g, "$1 {");
    
      // Indent lines ending with a semicolon
      formattedSource = formattedSource.replace(/^(.*?);/gm, "    $1;");
    
      return formattedSource;
    }
    
    console.log(prettyPrint(fn));
    

    Having said the above, the different developer tools have integrated options to pretty print the JavaScript sources within their debuggers.

    Firebug:

    Firebug pretty print button

    Firefox DevTools:

    Firefox DevTools pretty print button

    Chrome DevTools:

    Chrome DevTools pretty print button