JavaScript 字符串 concat() 方法
JavaScript 字符串 concat() 方法将两个或多个字符串参数连接到当前字符串。此方法不会更改现有字符串的值,而是返回一个新字符串。
您可以根据需要连接多个字符串参数。
语法
以下是 JavaScript 字符串 concat() 方法的语法 -
concat(str1, str2,......, strN)
参数
此方法接受多个字符串作为参数。与下文所述相同 -
- str1, str2,....., strN - 待连接的字符串。
返回值
此方法返回连接后的新字符串。
示例 1
在下面的程序中,我们使用 JavaScript 字符串的 concat() 方法连接两个字符串"Tutorials"和"Point"。
<html>
<head>
<title>JavaScript String concat() Method</title>
</head>
<body>
<script>
const str1 = "Tutorials";
const str2 = "Point";
const new_str = str1.concat(str2);
document.write("str1 = ", str1);
document.write("<br>str2 = ", str2);
document.write("<br>new_str(after concatenate) = ", new_str);
</script>
</body>
</html>
输出
上述程序在连接后返回一个新字符串"TutorialsPoint"。
str1 = Tutorials str2 = Point new_str(after concatenate) = TutorialsPoint
示例 2
以下是字符串 concat() 方法的另一个示例。在此示例中,我们连接多个字符串:"Welcome"、"to"、"Tutorials"和"Point",并使用空格将它们分隔开。
<html>
<head>
<title>JavaScript String concat() Method</title>
</head>
<body>
<script>
const str1 = "Welcome";
const str2 = "to";
const str3 = "Tutorials";
const str4 = "Point";
document.write("str1 = ", str1);
document.write("<br>str2 = ", str2);
document.write("<br>str3 = ", str3);
document.write("<br>str4 = ", str4);
const new_str = str1.concat(" ",str2," ",str3," ",str4);
document.write("<br>Concatenated string(with white-sapce separated) = ", new_str);
const new_str1 = str1.concat(str2,str3,str4);
document.write("<br>Concatenated string(without white-sapce separated) = ", new_str1);
</script>
</body>
</html>
输出
执行上述程序后,它将连接所有字符串并返回一个新字符串,如下所示:
str1 = Welcome str2 = to str3 = Tutorials str4 = Point Concatenated string(with white-sapce separated) = Welcome to Tutorials Point Concatenated string(without white-sapce separated) = WelcometoTutorialsPoint
示例 3
我们再看一个例子,了解如何使用 JavaScript 字符串 concat() 方法。使用此方法,我们可以连接字符串"Hello"和"World",并用逗号 (,) 分隔它们。
<html>
<head>
<title>JavaScript String concat() Method</title>
</head>
<body>
<script>
document.write("Hello".concat(", ", "World"));
</script>
</body>
</html>
输出
上述程序在输出中返回"Hello, World" -
Hello, World

