非常簡單,就用一個"+"將兩個字符串"相加":
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()方法顯然不如"+"來得直觀簡潔。