JavaScript concat() | Concatenate Two or More Strings

The JavaScript concat() method is used when we need to concatenate or join two or more strings. For example:

HTML with JavaScript Code
<!DOCTYPE html>
<html>
<body>

   <p>First string: <span id="one"></span></p>
   <p>Second string: <span id="two"></span></p>
   <p>String after joining first and second string: <span id="concat"></span></p>

   <script>
      let firstString = "codes";
      let secondString = "cracker";
      
      let concatString = firstString.concat(secondString);

      document.getElementById("one").innerHTML = firstString;
      document.getElementById("two").innerHTML = secondString;
      document.getElementById("concat").innerHTML = concatString;
   </script>
   
</body>
</html>
Output

First string:

Second string:

String after joining first and second string:

JavaScript concat() Syntax

The syntax of concat() method in JavaScript is:

string.concat(string1, string2, ..., stringN)

At least one string as argument to concat() method is required.

All the strings defined as arguments to concat() will be joined into the string, in same order as in the arguments. For example:

HTML with JavaScript Code
<!DOCTYPE html>
<html>
<body>

   <p id="xyz"></p>

   <script>
      let a = "codes";
      let b = "cracker";
      let c = ".";
      let d = "com";
      
      let x = a.concat(b, c, d);
      document.getElementById("xyz").innerHTML = x;
   </script>
   
</body>
</html>
Output

If you change the order of parameter, then returned string will be changed. For example:

HTML with JavaScript Code
<!DOCTYPE html>
<html>
<body>

   <p id="abc"></p>

   <script>
      let a = "codes";
      let b = "cracker";
      let c = ".";
      let d = "com";
      
      let x = a.concat(c, d, b);
      document.getElementById("abc").innerHTML = x;
   </script>
   
</body>
</html>
Output

That is, all strings provided as parameters to concat() will joined to the string that is provided before the concat() method. For example:

m.concat(n, o, p, q, r, s, t)

The returned string will be the value of m+n+0+p+q+r+s+t. Notice the first one, that is m.

JavaScript Online Test


« Previous Tutorial Next Tutorial »



Like/Share Us on Facebook 😋