Home > Web Front-end > JS Tutorial > How to concatenate characters to form a string in javascript

How to concatenate characters to form a string in javascript

青灯夜游
Release: 2023-01-07 11:46:32
Original
2276 people have browsed it

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.

How to concatenate characters to form a string in javascript

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”
Copy after login

Output result:

How to concatenate characters to form a string in javascript

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”
Copy after login

Output result:

How to concatenate characters to form a string in javascript

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);
Copy after login

Output result:

How to concatenate characters to form a string in javascript

[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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template