函数内巧用注释实现多行文本拼接

常常会遇到这么个场景,须要将html代码转为JavaScript输出。
通常的作法,就是使用字符串拼接或者使用数组拼接后最终转为字符串。javascript

常规作法:html

var str = '' +
'<!doctype html>' +
'<html>' +
'   <body>' +
'       <h1>函数内巧用注释实现多行文本拼接</h1>' +
'   </body>' +
'</html>' +
'';

之前,我通常是用转换工具实现,好比这个网址:HTML to JavaScript Convertorjava

用工具确实是个好方法,那有没有更好的解决方案?之前曾用过函数内用注射来实现本地调试的效果,那么注释是否也能够实现字符串拼接?git

实现方案:

function multiline(fn){
        var reCommentContents = /\/\*!?(?:\@preserve)?[ \t]*(?:\r\n|\n)([\s\S]*?)(?:\r\n|\n)[ \t]*\*\//;
    var match = reCommentContents.exec(fn.toString());
 
    if (!match) {
        throw new TypeError('Multiline comment missing.');
    }
 
    return match[1];
}

原理很是简单:github

  1. 在一个function中写上一段多行注释
  2. 将此function toString()
  3. 将多行注释内容用正则匹配出来

如何使用:

multiline(function(){/*
<!doctype html>
<html>
    <body>
        <h1>函数内巧用注释实现多行文本拼接</h1>
    </body>
</html>
*/});

函数执行后的输出结果:数组

<!doctype html>
<html>
    <body>
        <h1>函数内巧用注释实现多行文本拼接</h1>
    </body>
</html>

利用注射巧妙的省去了字符串拼接的烦恼,那么在实际项目中是否可用?
通常在实际项目上线前,js都须要压缩,而压缩后将致使正则提取失败。函数

如何防止注释被压缩工具去掉?工具

  1. uglify: 使用 /@preserve 代替 / 便可
  2. Closure Compiler(Google): 使用 /@preserve 代替 /
  3. YUI Compressor: 使用 /! 代替 /

若是须要压缩的话,可用以下方式输出:调试

multiline(function(){/*!@preserve
<!doctype html>
<html>
    <body>
        <h1>函数内巧用注释实现多行文本拼接</h1>
    </body>
</html>
*/});

项目地址:https://github.com/baofen14787/multilinecode

相关文章
相关标签/搜索