Javascript method of concatenating characters to form a string: 1. Use the " " plus operator, the syntax is "Character 1 Character 2"; 2. Use the concat() method, the syntax is "Character object 1.concat(Character 2,Character 3,Character 4..,Character n)"; 3. Use the join() method.
The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.
In JavaScript, there are three ways to concatenate (splice) characters to form a string. Let me introduce them one by one below.
Method 1: Use the " " plus sign operator
The easiest way to connect strings is to use the plus sign operator.
var s1 = "a" , s2 = "b" , s3 = "c" , s4 = "d" , s5 = "e" , s6 = "f" , s7 = "g"; console.log(s1 + s2 + s3 + s4 + s5 + s6 + s7); //返回字符串“abcdefg”
Output result:
Method 2: Use the concat() method
Use the string concat( ) method can add multiple parameters to the end of the specified string. There is no limit to the parameter type and number of this method. It will convert all parameters into strings, then concatenate them to the end of the current string in sequence and finally return the concatenated string.
var s1 = "a", s2 = "b", s3 = "c"; var s4 = s1.concat(s2 , s3 , "d" , "e" , "f"); //调用concat()连接字符串 console.log(s4); //返回字符串“abcdef”
Output result:
The concat() method does not modify the value of the original string, and is similar to the concat() method of the array.
Method 3: Use the join() method
In a specific operating environment, you can also use the join() method of the array to connect strings. Such as HTML string output, etc.
var s = "a" , a = []; for (var i = 0; i < 10; i ++) { a.push(s); } var str = a.join(""); a = null; console.log(str);
Output result:
[Recommended learning: javascript advanced tutorial]
The above is the detailed content of How to concatenate characters to form a string in javascript. For more information, please follow other related articles on the PHP Chinese website!