JavaScript中字符串拼接的基本方法
程序员文章站
2023-08-21 20:54:02
非常简单,就用一个"+"将两个字符串"相加":
var longstring = "one piece " + "plus one more piece."...
非常简单,就用一个"+"将两个字符串"相加":
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()方法显然不如"+"来得直观简洁。