JavaScript tidy

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, which there is no requirement for them to do. In fact, it relies on the browser decompiling to tidied code instead of just retaining the original, which is an expensive process in terms of performance, and leads to extra complexity when trying to make sure the decompiled code still works, so not all browsers choose to do it this way.

For best results, use Opera 9.2x- (not 9.5+) on this page. It partially works in Firefox 2 (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 3-. Since you can always keep a copy of Opera 9.27 on your computer (as well as whatever the current version is), I recommend you use Opera, and keep a copy of it around for use with JSTidy. (While it works in Safari 3- or Konqueror 3, they do not allow you to install old and new versions at the same time, so cannot be used on a computer that is also used for current Web development.)

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.