JavaScript tidy

http://www.howtocreate.co.uk/tutorials/jsexamples/JSTidy.html

Navigation

Skip navigation.

Site search

Site navigation

Script details

Tidying JavaScript code

If you have to debug scripts where the author has decided to compact everything onto one line, with all whitespace removed, this script can put the whitespace and control characters back, to make the script readable again. It can tidy most JavaScript to put in the correct indents, linebreaks, and semi-colons.

Several attempts have been made to produce programs to reformat code, but these often fail to cope with situations such as '{', '}' or ';' characters inside strings, regular expressions, or comments, so virtually all of them end up with broken code. However, browsers already have their own parsers built in that deal with all of these situations. This script hooks into the browser's own parser, by wrapping the code in a function then using the native toString method to obtain the tidied code. As a result, it relies on the browser producing a tidied output.

For best results, use Opera, Safari or Konqueror on this page. It partially works in Firefox (nested functions are not tidied, meaning that most scripts you want to tidy still end up unreadable), and fails to reformat code in IE and iCab.

To see the script license and check details like browser compatibility, use the links on the navigation panel at the top of this page.

Tidy your code

Put code to be tidied into the form below. Note that this should be valid code (in other words, if a function or control structure starts in it, it must end in it as well), and should not contain any HTML comments.

There is also a JSTidy bookmarklet on my bookmarklets page to automate tidying of all scripts on a page.

This site was created by Mark "Tarquin" Wilton-Jones.
Don't click this link unless you want to be banned from our site.