我有多个字符串,如下所示 -
var str1 = "this is a test that goes on and on"+param1
var str2 = "this is also a test this is also"+param2+" a test this is also a test this is also a tes"
var str3 = "this is also a test"
我将每个字符串分配给它自己的var,以保持代码可读,并防止字符串值跨越字符串。另外正如我所读到的那样,换行符javascript字符在所有浏览器中都不起作用 - Creating multiline strings in JavaScript
然后我把字符串连接起来 -
var concatStr = str1 + str2 + str3
并返回字符串连接值。
这是将大字符串分解为其部分的可接受方法吗?或者可以改进吗?
答案 0 :(得分:6)
无需将每一行分配到不同的变量:
var str1 = "this is a test that goes on and on"+param1 +
"this is also a test this is also"+param2+
" a test this is also a test this is also a tes" +
"this is also a test";
就个人而言,我会做以下事情:
var string = ['hello ', param1,
'some other very long string',
'and another.'].join('');
对我来说,输入和阅读更容易。
答案 1 :(得分:1)
如果你使用非常长的字符串,那么将它的一部分保存在一个数组中然后加入它们:
ARRAY = ['I', 'am', 'joining', 'the', 'array', '!'];
ARRAY.join(' ');
结果:
"I am joining the array !"
请记住,如果您需要在客户端JavaScript中执行此操作,那么可能您做错了。 :)
答案 2 :(得分:0)
您可以使用数组。它的join方法是连接字符串的最快方法。
var myArray = [
"this is a test that goes on and on"+param1,
"this is also a test this is also"+param2+" a test this is also a test this is also a tes",
"this is also a test"
];
然后使用:
myArray.join('');
获取完整的字符串。