一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

Javascript实现Heredoc语法 及大量字符串拼接实现

时间:2015-01-20 编辑:简简单单 来源:一聚教程网

在php、python中都有heredoc方式的字符串定义方法:

php:

 代码如下 复制代码
$sql=<< select *
from pages
where pagename='$pn'
EOD;

python:

 代码如下 复制代码
print """
This is an example of a string in the heredoc syntax.
This text can span multiple lines
"""

js拼接大量字符串没个heredoc风格的操作符是比较繁琐的:

拼接方式一:

 代码如下 复制代码
var str = "
Here is line one
And line two
Finally, line three!
";

alert(str);

拼接方式二:

'+
            ''+
            ''+
            ''+
            ''+
            ''+
            ''+
            '';
 代码如下 复制代码
 var __template =
        '
#salarySN##name##TDR_NAME##TSD_NAME##WORK_STATUS##isleader_display#'
                +'javascript:void(-1)">设置角色'
        +'


JS字符串需要打破原字符串风格,每行处理,这点有点让人受不了。

给个解决方案:

 代码如下 复制代码
function aHereDoc() {/*
Hello, World!
I am a JavaScript here document.
Use the 'hereDoc' function to extract me.
*/}

function hereDoc(func) {
return func.toString().split(/n/).slice(1, -1).join('n');
}
console.log(hereDoc(aHereDoc));


利用func.toString()获取需要批量处理的字符串,利用split(/n/).slice(1, -1)去掉首尾两行函数定义的代码,重新组装即可。

refer:http://trentrichardson.com/2010/11/11/javascript-heredoc-like-syntax/

热门栏目