JavaScript利用Function注释实现多行HTML字符串存储

作者:竹影

时间:2026-10-28

浏览:106

本文介绍一种在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);

实用工具推荐

电子包浆

绿化、压缩、噪点和虚拟水印,自由调节做旧程度。

使用 ›
图片压缩

选择画质和输出格式,预览压缩前后的大小。

使用 ›
相关文章