如何在JavaScript中进行格式化/整洁/美化 [英] How to format/tidy/beautify in JavaScript

查看:193
本文介绍了如何在JavaScript中进行格式化/整洁/美化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在JavaScript中格式化/整理/美化HTML? 我曾尝试搜索/替换尖括号(< > )并相应地进行缩进。但是当然它并没有考虑到JS或CSS等。

How can I format/tidy/beautify HTML in JavaScript? I have tried doing a search/replace for angle brackets (<, >) and indenting accordingly. But of course it does not take into account when the is JS or CSS etc inside the HTML.

我想这样做的原因是我制作了一个内容编辑器(CMS),它具有所见即所得和源代码视图。所见即所得编辑器编写的代码通常是单行的问题。所以我想要一个JavaScript,可以将其格式化为更具可读性的形式。

The reason I want to do this is 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.

这里我到目前为止:

Here what I have so far:

function getIndent(level) {
    var result = '',
        i = level * 4;
    if (level < 0) {
        throw "Level is below 0";
    }
    while (i--) {
        result += ' ';
    }
    return result;
}

function style_html(html) {
    html = html.trim();
    var result = '',
        indentLevel = 0,
        tokens = html.split(/</);
    for (var i = 0, l = tokens.length; i < l; i++) {
        var parts = tokens[i].split(/>/);
        if (parts.length === 2) {
            if (tokens[i][0] === '/') {
                indentLevel--;
            }
            result += getIndent(indentLevel);
            if (tokens[i][0] !== '/') {
                indentLevel++;
            }

            if (i > 0) {
                result += '<';
            }

            result += parts[0].trim() + ">\n";
            if (parts[1].trim() !== '') {
                result += getIndent(indentLevel) + parts[1].trim().replace(/\s+/g, ' ') + "\n";
            }

            if (parts[0].match(/^(img|hr|br)/)) {
                indentLevel--;
            }
        } else {
            result += getIndent(indentLevel) + parts[0] + "\n";
        }
    }
    return result;
}


推荐答案

@lovasoa 如何格式化/整理/美化JavaScript 是一个很好的解决方案。 >
坚如磐石,比vkBeautify甚至CodeMirror(难以使用AMD)好得多,而且非常容易

@lovasoa How to format/tidy/beautify in JavaScript is an excellent solution.
rock-solid, much better than vkBeautify or even CodeMirror (hard to use AMD) and VERY easy

<script src='http://lovasoa.github.io/tidy-html5/tidy.js'></script>
<script>
  options = {
  "indent":"auto",
  "indent-spaces":2,
  "wrap":80,
  "markup":true,
  "output-xml":false,
  "numeric-entities":true,
  "quote-marks":true,
  "quote-nbsp":false,
  "show-body-only":true,
  "quote-ampersand":false,
  "break-before-br":true,
  "uppercase-tags":false,
  "uppercase-attributes":false,
  "drop-font-tags":true,
  "tidy-mark":false
}

var html = document.querySelector("body").outerHTML;
var result = tidy_html5(html, options);
console.log(result);
</script>

这篇关于如何在JavaScript中进行格式化/整洁/美化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆