如何将html代码转换为字符串,将换行符替换为 ,将制表符替换为

How to convert html code to a string that replaces the newlines with and tabs with

本文关键字:替换 制表符 字符串 换行符 转换 html 代码      更新时间:2023-09-26

是否有一种简单的方法将以某种方式结构化的HTML代码转换为单个字符串(然后可以在Javascript变量中使用)。html代码中的新行和制表符需要转换为'n和't,以便格式化可以保持原状。

HTML例子:

<html>
    <head>
         <title>Hello World</title>
    </head>
    <body>
        <h1>Title</h1>
            <h2>Subtitle</h2>
                <p>Some text goes here</p>
    </body>
 </html>

我已经手动将其转换为:

<html>'n'n't<head>'n't't <title>Hello World</title>'n 't</head>'n'n 't<body>'n 't't<h1>Title</h1>'n 't't't<h2>Subtitle</h2>'n 't't't't<p>Some text goes here</p>'n 't</body>'n'n </html>'n

是否有一个简单的方法来自动做到这一点?因为我需要将较大的HTML块转换为这种格式。谢谢。

    function format(data) {
        var returnStr = "";
        var lines = data.split("'n");
        var block = [];
        for (var i = 0; i < lines.length; i++) {
            block = lines[i].split(''t');
            for (var j = 0; j < block.length; j++) {
                returnStr += block[j];
                if (block.length>1) {
                    returnStr +=  "''t";
                }
            };
            returnStr +=  "''n";
        };
        return returnStr;
    }

如果您这样做是为了在html中显示换行符和回车符,那么您不需要显式地这样做。在css中可以通过设置空格属性的前置值来实现。

<span style="white-space: pre-line">CommentText</span>