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

以下是 String 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
廣告