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

  作者:bea

在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 ""
在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(/
/).slice(1, -1).join('
'); } console.log(hereDoc(aHereDoc));

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



有用  |  无用

猜你喜欢