Tidy HTML output with JavaScript
Asked Answered
M

2

6

I have a large chunk of HTML. In order for it to fit a certain container, I crop the HTML (not just the text) at, let’s say, 200 characters. Obviously, some of the tags will remain unclosed in this case. Is there a way, except writing the cleaner myself, to clean such cropped snippet without the server being involved?

Online services with public APIs that I can use from JavaScript are acceptable.

Metry answered 20/2, 2012 at 20:42 Comment(0)
K
2

You can try the cutter.js library. It's pretty new, so I haven't heard much about it, but it seems like what you're looking for as far as cropping goes.

Check out my fiddle, testing it out: http://jsfiddle.net/JKirchartz/jwL8v/

var oElement = document.getElementById("test");
Cutter.run(oElement, oElement, 100);

$("#gc").click(function(){
    /* This will count words by spaces in the text */
    var tt = $("#test").text().split(" ");
    if (typeof(console) == 'object'){    
        console.log(tt);
    }
    alert("wordcount: "+tt.length);
     
});
Kipton answered 23/2, 2012 at 14:9 Comment(3)
cutter.js looks promising. Thanks for the link. Though, I have tried to play with your fiddle and I found nWords param (100 in your example) absolutely unreliable. When I set it to 1 I get the whole text back. When I set it to 10, I get the header only. 57 gives me much more text than 60 and so on. Probably I need to play more with it but it is a good start. Thanks!Metry
I've updated the fiddle with an elementary word-counter, and the numbers are wonky. Like I said this is a new plugin, so it might take a couple of updates for it to be perfect.Kipton
Meant to mention, cutter is on github, so you can fork it modify the code and contribute to the project if you wish. Community is awesome.Kipton
E
0

The Google Closure library has an HTML Pretty Printer module. You should be able to fork off it:

Closure Library

Also, if you are using jQuery, try http://www.davidpirek.com/blog/html-beautifier-jquery-plugin.

Evante answered 23/2, 2012 at 14:4 Comment(2)
Thanks for the links. But I don't really need a beautyfier. HTML can be as ugly as it gets unless it is cropped and all the cropped tags are closed.Metry
The second link seems to be broken (times out): "504 ERROR. The request could not be satisfied."Larva

© 2022 - 2024 — McMap. All rights reserved.