23

Given a string like this:

' \n <div id="a">\n <span class="b">\n<span>Hello</span>\n\n\n</span> <input type="text">\n  \n</div>\n '

I'd like to format it like this:

<div id="a">
  <span class="b">
    <span>Hello</span>
  </span>
  <input type="text">
</div>

i.e. the result should be: (assume 2 spaces for indentation)

'<div id="a">\n  <span class="b">\n    <span>\n      Hello\n    </span>\n  </span>\n  <input type="text">\n</div>'

What's the most elegant way to achieve this? Is there an established way to do that?

Note:

  • I'm not looking for HTML syntax highlighting, just indentation correction
  • I'm not looking to support the whole HTML spec, correcting basic HTML like the example above would suffice
14
  • 1
    What would you do if the input is <div><span></div></span>? Oct 14, 2014 at 12:07
  • 7
    @NiettheDarkAbsol probably cry because that is invalid html!
    – Pete
    Oct 14, 2014 at 12:08
  • 1
    I don't really care about invalid HTML, so any result will be good enough. Oct 14, 2014 at 12:09
  • 1
    @MishaMoroshko Personally, I would suggest parsing the HTML string into a DOM object, and then reconstructing the HTML in the format that you want. This may seem like a daunting task, but it will be significantly easier than trying to manipulate strings. Oct 14, 2014 at 12:10
  • 1
    @RichBradshaw I use prismjs to highlight an HTML fragment and show it to the user. The problem is that prismjs doesn't fix the indentation for me, so I need to do this myself before passing the HTML string to prismjs for highlighting. Oct 14, 2014 at 12:26

3 Answers 3

44

Here is a simple recursive function I wrote, which I think might help you to achieve what you are after.

function process(str) {

    var div = document.createElement('div');
    div.innerHTML = str.trim();

    return format(div, 0).innerHTML;
}

function format(node, level) {

    var indentBefore = new Array(level++ + 1).join('  '),
        indentAfter  = new Array(level - 1).join('  '),
        textNode;

    for (var i = 0; i < node.children.length; i++) {

        textNode = document.createTextNode('\n' + indentBefore);
        node.insertBefore(textNode, node.children[i]);

        format(node.children[i], level);

        if (node.lastElementChild == node.children[i]) {
            textNode = document.createTextNode('\n' + indentAfter);
            node.appendChild(textNode);
        }
    }

    return node;
}

Then you would use it like this:

process(str);

Here is a demo:

var str = '<div id="a"><span class="b"><span>Hello</span></span><input type="text"><p><b>b <i>italic</i></b></p></div>';

function process(str) {
  var div = document.createElement('div');
  div.innerHTML = str.trim();

  return format(div, 0).innerHTML;
}

function format(node, level) {
  var indentBefore = new Array(level++ + 1).join('  '),
    indentAfter = new Array(level - 1).join('  '),
    textNode;

  for (var i = 0; i < node.children.length; i++) {
    textNode = document.createTextNode('\n' + indentBefore);
    node.insertBefore(textNode, node.children[i]);

    format(node.children[i], level);

    if (node.lastElementChild == node.children[i]) {
      textNode = document.createTextNode('\n' + indentAfter);
      node.appendChild(textNode);
    }
  }

  return node;
}

document.querySelector('#out').innerText = process(str);
<pre id="out"></pre>

Demo: http://jsfiddle.net/1gf07wap/

3
  • Thanks! Looks close to what I'm looking for. However, your function creates too many new lines. Have a look at these 2 example inputs: jsfiddle.net/3gLxLhs3 Oct 15, 2014 at 3:49
  • It's because you input has weird new lines and spaces. it's easy to fix the function to remove leading white spaces though.
    – dfsq
    Oct 15, 2014 at 6:16
  • thanks, u saved my day :)
    – Rana
    Aug 3, 2017 at 14:45
6

The js-beautify tool can work with html, and has an api. It's probably the easiest way to do what you want.

After installing it with node:

var beautify_html = require('js-beautify').html;

result = beautify_html(htmlstring);

To use it in a browser, you need to include all the beautify*.js scripts in this directory and use window.html_beautify.

DEMO

7
  • This beautifier sucks, for example, when you input <!doctype html><head><title> </title><ul><li>a<li>b</ul>, you get incorrect results. Downvote from me.
    – user1180790
    Oct 14, 2014 at 12:29
  • @Benio Really? I believe it's the same thing used here, and it gives a good result to me.
    – parchment
    Oct 14, 2014 at 12:31
  • Yes. I tested it right on this site. The second li is incorrectly more indented than the first one. <!doctype html>\n\n<head>\n\t<title> </title>\n\t<ul>\n\t\t<li>a\n\t\t\t<li>b</ul> is not a good indentation.
    – user1180790
    Oct 14, 2014 at 12:32
  • @Benio That's because your HTML doesn't have any closing tags, and it thinks that the li is inside the other li. It only works in browsers because the parser in browsers are more lenient. You can't really expect much from invalid html.
    – parchment
    Oct 14, 2014 at 12:35
  • 2
    @parchment the closing li tag is optional so the only thing invalid about the code Benio has pasted is that it does not have body tags and a closing head tag. From the spec: An li element’s end tag may be omitted if the li element is immediately followed by another li element or if there is no more content in the parent element.
    – Pete
    Oct 14, 2014 at 13:35
1

Since there are lots of complains about js-beautify, I'm posting this alternative:

GIT: https://github.com/maxogden/commonjs-html-prettyprinter

DEMO: http://requirebin.com/?gist=45056f6a9b306a14ea3d

CODE:

var htmlmodule = require('html');
var str = ' \n <div id="a">\n <span class="b"><span>Hello</span></span><input type="text">\n  \n</div>\n ';
var pretty = htmlmodule.prettyPrint(str);

IF this does not work as you intend to, I recommend parsing the HTML string... for this job you can use this xmldom parseFromString... it's really simple.

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.