The basic method of string concatenation in JavaScript
- 2020-07-21 06:52:13
- OfStack
Very simply, use 1 "+" to "add" two strings:
var longString = "One piece " + "plus one more piece.";
To accumulate multiple strings into a single string, you can also use the "+=" operator:
var result = "";
result += "My name is Anders"
result += " and my age is 25";
To add a newline character to a string, you need to use the escape character "" :
var confirmString = "You did not enter a response to the last " +
"question.Submit form anyway?";
var confirmValue = confirm(confirmString);
However, this method can only be used in situations such as warning, confirmation dialog, etc. If the text is rendered as HTML content, it will be invalid.
<
br
>
"Instead of it:
var htmlString = "First line of string.<br>Second line of string.";
document.write(htmlString);
The String object also provides the method concat(), which does the same thing as "+" :
string.concat(value1, value2, ...)
But the concat() method is certainly not as straightforward as the + method.