Javascript中拼接大量字符串的方法

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

php:


$sql=<<<EOD

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 = 

            '<tr>'+

                '<td>#salarySN#</td>'+

                '<td>#name#</td>'+

                '<td>#TDR_NAME#</td>'+

                '<td>#TSD_NAME#</td>'+

                '<td>#WORK_STATUS#</td>'+

                '<td>#isleader_display#</td>'+

                '<td>'

                    +'<a href="javascript:void(-1)">设置角色</a>'

            +'</td></tr>';


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)去掉首尾两行函数定义的代码,重新组装即可。