DWQA QuestionsCategory: ProgramHTML string typesetting
Clark asked 5 days ago

I have it now.HTMLIs there any available way to typeset the code string?
We need a JS plug-in, or method, which can be used for transformation in the project.
For example, the original string is:

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

Add spaces and line breaks to make a new string:

<div>
    <p>This is a p</p>
    <p>This is another p</p>
</div>
4 Answers
Best Answer
mqycn answered 5 days ago

The first scheme is not successful.
I have sorted out the following ideas and solved them perfectly.

function codeFormat(code, indent, tmpIndent){
    var indent = indent || '  ';
    var tmpIndent = tmpIndent || '\n';
    var preg = /<(\S*)([^>]*)>([\s\S]*?)<\/>/ig;
    return code.replace(preg, function($0, $1, $2, $3){
        return tmpIndent + '<' + $1 + $2 + '>'
            + codeFormat($3, indent, tmpIndent + indent)
            + ( $3.trim().substr(0,1) == '<' ? tmpIndent : '') 
            + '</' + $1 + '>';
    });
}
codeFormat("<div><p>This is a p</p><p>This is anothers p</p></div><div><p>This is a p</p><p>This is another p</p></div>");
/*
<div>
  <p>This is a p</p>
  <p>This is anothers p</p>
</div>
<div>
  <p>This is a p</p>
  <p>This is another p</p>
</div>
*/
codeFormat('<html><head><title></title></head><body class="haha"><div style="background:#C00;"><p>This is a p</p><p>This is another p</p></div></body></html>', '----');
/*
<html>
----<head>
--------<title></title>
----</head>
----<body class="haha">
--------<div style="background:#C00;">
------------<p>This is a p</p>
------------<p>This is another p</p>
--------</div>
----</body>
</html>
*/

Here is the old answer to the cycle:

/*
    I don't think it's difficult. It's a cycle
    Meet > followed by <, line break
    Meet < indent
    Encounter < / cancel indent
*/
function codeFormat(code, indent){
    Var indent = indent | // indent character
    Var tmpindent = ""; // save the code string
    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("<div><p>This is a p</p><p>This is another p</p></div>");
/*
<div>
  <p>This is a p</p>
  <p>This is another p</p>
</div>
*/
codeFormat('<html><head><title></title></head><body class="haha"><div style="background:#C00;"><p>This is a p</p><p>This is another p</p></div></body></html>', '    ');
/*
<html>
    <head>
        <title>
        </title>
    </head>
    <body class="haha">
        <div style="background:#C00;">
            <p>This is a p</p>
            <p>This is another p</p>
        </div>
    </body>
</html>
*/
mqycn replied 5 days ago

Regular scheme updated

Clark answered 5 days ago

Why am I being trampled on? It’s 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');
}
linong answered 5 days ago

http://tool.oschina.net/codef&#8230;Online. Other editors include beauty
clipboard.png

ewind answered 5 days ago
  1. For development tools, you can try the vscode editor.

https://code.visualstudio.com/
After the installation is completed, press shift-ctrl-x to open the plug-in list, search beautify and install to beautify the HTML code.
The corresponding settings are as follows:
https://marketplace.visualstu&#8230;

  1. For format conversion in code, HTML string parser can be used, for example

https://www.npmjs.com/package&#8230;
Or use cheerio to parse DOM text and output again.
3. (it’s not difficult to remake an HTML parser. Please refer to my column
http://ewind.us/2016/toy-html&#8230;