search

Home  >  Q&A  >  body text

HTML string typesetting - Stack Overflow

I now have a string of HTML code, and I want to format the string. Is there any available method?

You need a js plug-in or method that can be used for conversion in the project.

For example, the original string is:

<p><p>This is a p</p><p>This is another p</p></p>

Add spaces and newlines to become a new string:

<p>
    <p>This is a p</p>
    <p>This is another p</p>
</p>
迷茫迷茫2736 days ago797

reply all(4)I'll reply

  • 世界只因有你

    世界只因有你2017-05-24 11:38:25

    The first solution was to use regular expressions to answer the question, but it didn’t work.
    I sorted out my thoughts and have solved it perfectly (I think it is perfect).

    function codeFormat(code, indent, tmpIndent){
        var indent = indent || '  ';
        var tmpIndent = tmpIndent || '\n';
        var preg = /<(\S*)([^>]*)>([\s\S]*?)<\/>/ig;
        return code.replace(preg, function(
    /*
        感觉没什么难度,一个循环
        遇见 >后跟<,换行
        遇见 < 缩进
        遇见 </ 取消缩进
    */
    function codeFormat(code, indent){
        var indent = indent || "  ";    //缩进字符
        var tmpIndent = "";    //保存代码字符串
        var result = "", key = "", keyNext = "";
        for( var i = 0 ; i < code.length ; i++ ){
            key = code[i];
            keyNext = i < code.length-1 ? code[i+1] : "";
            if(key == "<"){
                if( keyNext == "/" ){
                    tmpIndent = tmpIndent.substr(indent.length);
                }
                if( result[result.length-1] == "\n" ){
                    result += tmpIndent;
                }
                if( keyNext != "/" ){
                    tmpIndent += indent;
                }
            }
            result += key;
            if(key == ">" && keyNext == "<" ){
                result += "\n";
            }
        }
        return result;
    }
    
    codeFormat("<p><p>This is a p</p><p>This is another p</p></p>");
    /*
    <p>
      <p>This is a p</p>
      <p>This is another p</p>
    </p>
    */
    codeFormat('<html><head><title></title></head><body class="haha"><p style="background:#C00;"><p>This is a p</p><p>This is another p</p></p></body></html>', '    ');
    /*
    <html>
        <head>
            <title>
            </title>
        </head>
        <body class="haha">
            <p style="background:#C00;">
                <p>This is a p</p>
                <p>This is another p</p>
            </p>
        </body>
    </html>
    */
    , , , ){ return tmpIndent + '<' + + + '>' + codeFormat(, indent, tmpIndent + indent) + ( .trim().substr(0,1) == '<' ? tmpIndent : '') + '</' + + '>'; }); } codeFormat("<p><p>This is a p</p><p>This is anothers p</p></p><p><p>This is a p</p><p>This is another p</p></p>"); /* <p> <p>This is a p</p> <p>This is anothers p</p> </p> <p> <p>This is a p</p> <p>This is another p</p> </p> */ codeFormat('<html><head><title></title></head><body class="haha"><p style="background:#C00;"><p>This is a p</p><p>This is another p</p></p></body></html>', '----'); /* <html> ----<head> --------<title></title> ----</head> ----<body class="haha"> --------<p style="background:#C00;"> ------------<p>This is a p</p> ------------<p>This is another p</p> --------</p> ----</body> </html> */

    Here is the old answer for loops:

    rrreee

    reply
    0
  • 怪我咯

    怪我咯2017-05-24 11:38:25

    Why does this question of mine keep getting downvoted? Still a good question. . . .
    @mqycn , @zhenguoli

    This is a plan written by my friend @candy:

    import _ from 'lodash';
    
    const splitOnTags = str => str.split(/(<\/?[^>]+>)/g).filter(line=>line.trim()!="");
    const isTag = str => /<[^>!]+>/.test(str);
    const isClosingTag = str => /<\/[^>]+>/.test(str);
    const isSelfClosingTag = str => /<[^>]+\/>/.test(str);
    const isOpeningTag = str => isTag(str) && !isClosingTag(str) && !isSelfClosingTag(str);
    
    export default (str, indent) => {
      let depth = 0;
      indent = indent || '    ';
    
      return splitOnTags(str).map(item=>{
        if(isClosingTag(item)) {
          depth--;
        }
    
        const line = _.repeat(indent, depth) + item;
    
        if(isOpeningTag(item)) {
          depth++;
        } 
    
        return line;
      }).join('\n');
    }

    reply
    0
  • 黄舟

    黄舟2017-05-24 11:38:25

    http://tool.oschina.net/codef... online. Other editors include beauty

    reply
    0
  • 伊谢尔伦

    伊谢尔伦2017-05-24 11:38:25

    1. For development tools, you can try the VSCode editor.

    https://code.visualstudio.com/

    After the installation is complete, press shift-ctrl-x to open the plug-in list, search for Beautify and install it to beautify HTML code.
    Refer to here for the corresponding settings:

    https://marketplace.visualstu...

    1. For format conversion in code, you can use HTML String Parser, such as

    https://www.npmjs.com/package...

    Or you can use cheerio to parse the DOM text and re-output it.

    3. (It is not difficult to re-create an HTML Parser, refer to my column
    http://ewind.us/2016/toy-html...

    reply
    0
  • Cancelreply