本文介绍一种在JavaScript中通过Function对象的注释特性来存储多行HTML字符串的方法。利用toString()获取函数源码,并提取/* */注释内容,可避免字符串转义问题,适用于简单的HTML模板定义场景。
JavaScript利用Function注释实现多行HTML字符串存储
具体实现代码如下所示:
Function.prototype.heredoc = function(){
// 该方法利用函数注释来存储字符串,且无需进行转义处理。
var _str = this.toString(),
s_pos = _str.indexOf("/*")+2,
e_pos = _str.lastIndexOf("*/");
return (s_pos<0 || e_pos<0) ? "" : _str.substring(s_pos, e_pos);
}
function fn(){
/*<table>
<tr>
<td>用户名</td>
<td>密码</td>
</tr>
<tr>
<td style="widht:20px;">@name</td>
<td>zf123456</td>
</tr>
</table>*/
}
varstr_table=fn.heredoc();
console.log(str_table);