Heim  >  Artikel  >  Web-Frontend  >  Javascript中拼接大量字符串的方法_javascript技巧

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

WBOY
WBOYOriginal
2016-05-16 16:15:341273Durchsuche

在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#'+
                ''
                    +'设置角色'
            +' ';

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)去掉首尾两行函数定义的代码,重新组装即可。
Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn