views:

219

answers:

6

Is there any HTML formatter/tidy/beautifier out there written in JavaScript?

I have made a content editor (CMS) which has both WYSIWYG and source code views. The problem the code written by the WYSIWYG editor is normally a single line. So I would like a JavaScript that could format this into a more readable form on demand.

A: 

You could have a look at David Pireks approach - even though I think this is far from perfect.. (dependent on jQuery)

pex
Just tried it now, the code seems to have syntax errors.
Petah
+1  A: 

Is this what you want:

http://www.textfixer.com/html/uncompress-html-code.php

Here's the link to the decompressing javascript:

http://www.textfixer.com/js/uncompress-html-code.js

Steve
Its not ideal, it doesn't format it as I would expect, and it doesn't indent.
Petah
Just a few extra lines and it will... :)
Steve
+8  A: 

You may find this to be useful:

http://github.com/einars/js-beautify

It is the source code powering the site http://jsbeautifier.org/

ghoppe
This is not what I needed, I need one that formats HTML, not JavaScript
Petah
Umm… it does **both**: http://github.com/einars/js-beautify/blob/master/beautify-html.js -- try pasting pure html code into http://jsbeautifier.org/
ghoppe
A: 

Writing the HTML on one line would download faster to the browser, so I am not sure I would want it formatted. Maybe an option for a formatted version or an optimized version.

As for the question... you could do an AJAX call after so many actions and send the code to the server to be formatted and shown in a different box on the screen. Basically it would be a real time version of this site, http://infohound.net/tidy/

Eric
Yes it would be ever so slightly faster (like 0.0001 of a second). But considering a WYSIWYG editor is aimed at clients that know only a little about HTML, formatted HTML makes it a lots easier. Also in regards to sending the data to the server for formatting, that is far from ideal.
Petah
A: 

jQuery creator John Resig wrote a fast and lightweight HTML parser in javascript. If you're looking for a solution which you can add directly to your CMS then you could write a simple beautifier using this parser as a base. All you'd need to do is reoutput the elements adding spaces and line breaks as you like, using the built in api:

HTMLParser(htmlString, {
  start: function(tag, attrs, unary) {},
  end: function(tag) {},
  chars: function(text) {},
  comment: function(text) {}
});

An added benefit of this approach is that you could use the same HTMLParser to read HTML back into your WYSIWYG, or otherwise interact with your user's HTML tree. HTMLParser also comes prebuilt with an HTMLtoDOM method.

Daniel Mendel
A: 

I believe that both chrome and firebug's debugging code display engines are written in JS. That's probably heavier duty than you really want to be messing with though.

Paul McMillan