如果在一行的话,可读性太差;如果换行的话,会直接报错。
现在就来介绍几个JavaScript拼接字符串的几个小技巧(主要针对字符串过长的情况)。
1. 字符串相加(+)
1
2
3
var empList = ' <li data-view-section="details">'+
'<span>Hello world</span>'+
'</li>'
2.利用反斜杠拼接字符串
1
2
3
var empList = ' <li data-view-section="details">\
<span>Hello world</span>\
</li>'
3. 利用数组拼接字符串
复制代码代码如下:
var empList = ['<li data-view-section="details">', '<span>Hello world</span>','</li>'].join("")
利用数组的join方法,把数组转成字符串
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
function StringBuffer(){
this.buffer = []
}
//将新添加的字符串添加到数组中
StringBuffer.prototype.append = function(str){
this.buffer.push(str)
return this
}
//转成字符串
StringBuffer.prototype.toString = function(){
return this.buffer.join("")
}
//用法
var buffer = new StringBuffer()
buffer.append("hello")
buffer.append(',world')
console.log(buffer.toString())
在数组方法的基础上可以封装一个类似Java中的StringBuffer的类来完成字符串的拼接。
以上所述就是本文的全部内容了
用一个"+"将两个字符串"相加":var longString = "One piece " + "plus one more piece."
要将多个字符串累积为一个字符串,还可以使用"+="操作符:
var result = ""
result += "My name is Anders"
result += " and my age is 25"
要在字符串中添加换行符,需要使用转义字符"":
var confirmString = "You did not enter a response to the last " +
"question.Submit form anyway?"
var confirmValue = confirm(confirmString)
但这种方法只能用在像警告、确认对话框之类的情况下,如果将这段文本作为HTML内容呈现,就无效了,此时用"<br>"代替它:
var htmlString = "First line of string.<br>Second line of string."
document.write(htmlString)
String对象还提供了方法concat(),它完成与"+"相同的功能:
string.concat(value1, value2, ...)
不过concat()方法显然不如"+"来得直观简洁。
用js如何给字符串中加换行符的具体操作步骤如下:
1、首先,在文件夹下创建index.html文件,然后在html文件中添加基本的页面标签:
2、然后,在内部的循环中,每执行一次,就给字符串添加一个换行符,然后最后通过弹窗的方式将字符串显示出来:
3、之后,编辑好index.html文件后,使用浏览器打开index.html文件,可以看到,弹出的窗口,将四个名字显示成了两行,说明换行成功:
4、通常使用js都是会将数据显示在html页面上,这时换行符就不能用"\n"了,此时应该使用"<br />"。修改index.html文件:
5、最后,修改完index.html文件后,再次使用浏览器打开index.html文件,这样就成功在页面上显示用js处理过的字符串了: