This article will give you a summary of the javascript String concatenation method. In js, you can not only directly use + to connect strings, but also use related functions. The following is a tutorial.
String concatenation is common in JS. Sometimes it is troublesome to splice long strings. For example, an html string;
| The Code is as follows: |
Copy code |
Var str = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ";
Var str = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa "; |
The editor is limited in width. To make it readable, you must wrap the string. However, if you wrap the text below, an error is reported.
| The Code is as follows: |
Copy code |
Var str = "aaaaaaaaaaaaaaaaaaa Aaaaaaaaaaaaaaaaaaaaaa Aaaaaaaaaaaaaaaaaaaaaa "; var str =" aaaaaaaaaaaaaaaaaaa Aaaaaaaaaaaaaaaaaaaaaa Aaaaaaaaaaaaaaaaaaaaaa "; |
At this time, you need to splice strings. The most basic method is:
| The Code is as follows: |
Copy code |
Var str = "aaaaaaaaaaaaaaaaaa" + "Aaaaaaaaaaaaaaaaaaaaaa" + "Aaaaaaaaaaaaaaaaaaaaaaa"; var str = "aaaaaaaaaaaaaaaaaa" + "Aaaaaaaaaaaaaaaaaaaaaa" + "Aaaaaaaaaaaaaaaaaaaaaaa "; |
If there are only two or three rows, it would be better to have dozens of rows, which is not only time-consuming and laborious, but also prone to errors.
String concatenation techniques, using Arrays for character concatenation:
| The Code is as follows: |
Copy code |
Var strArr = []; StrArr. push ("aaaaaaaaaaaaaaaaaa "); StrArr. push ("aaaaaaaaaaaaaaaaaaaaaa "); StrArr. push ("aaaaaaaaaaaaaaaaaaaaaaa "); StrArr. join (""); var strArr = []; StrArr. push ("aaaaaaaaaaaaaaaaaa "); StrArr. push ("aaaaaaaaaaaaaaaaaaaaaa "); StrArr. push ("aaaaaaaaaaaaaaaaaaaaaaa "); StrArr. join (""); |
This method reduces the probability of errors, but the amount of work is still small.
More convenient String concatenation methods:
Line feed directly in the string will produce an error, but if you add a backslash "" after each line, it will not produce an error;
| The Code is as follows: |
Copy code |
Var str = "aaaaaaaaaaaaaaaaaa Aaaaaaaaaaaaaaaaaaaaaa Aaaaaaaaaaaaaaaaaaaaaaa "; // Do not add the backslash var str = "aaaaaaaaaaaaaaaa" to the last line Aaaaaaaaaaaaaaaaaaaaaa Aaaaaaaaaaaaaaaaaaaaaaa ";
|
// The last line does not need to be added with a backslash. Of course, this method also has a disadvantage, that is, it cannot be followed by a single line comment.
As for the performance comparison between these methods, I don't think we should consider it too much. Unless there are thousands of lines of String concatenation, the performance gap will be negligible; the readability of the program should be put in front.