JavaScript String concat() Method
The concat() method in JavaScript join or concatenate two or more strings together. It does not change the existing strings and returns a new string. This method efficiently combines multiple strings into one, ensuring the original strings remain unchanged.
Syntax
str1.concat(str2, str3, str4,......, strN)
Parameters
- str1, str2, ..., strN: This method accepts the string paramters that need to be joined together. The number of arguments to this function is equal to the number of strings to be joined together.
Note: If the parameters are not of String type, then first it converted to string before concatenating the strings.
Return value
Returns a new string that is the combination of all the different strings passed to it as the argument.
Example 1: Join Two Strings with concat() Method
The string "str" is initialized with the value "Welcome". Then concat() method is used on str to combine it with "Geeks".
// JavaScript String concat() method
// to merge strings together
// First string
let str = "Welcome";
// Joining the strings together
let concatStr = str.concat(" Geeks");
console.log(concatStr);
Output
Welcome Geeks
Example 2: Concatenating Multiple Strings with concat() Method
The concatenates strings str1
, str2
, and str3
together. The result1
combines them without spaces, while result2
concatenates them with spaces.
let str1 = 'Geeks'
let str2 = 'For'
let str3 = 'Geeks'
// Concating all the strings together without spaces
let result1 = str1.concat(str2, str3)
console.log('Result without spaces: ' + result1)
// Concating all the strings together with spaces
let result2 = str1.concat(' ', str2, ' ', str3)
console.log('Result with spaces: ' + result2)
Output
Result without spaces: GeeksForGeeks Result with spaces: Geeks For Geeks
Eample 3: Concatenate with Empty Strings
You can use the concat() method with empty strings to control the formatting or add spaces dynamically
const str1 = "Hello";
const str2 = "";
const str = str1.concat(str2);
console.log(str);
Output
Hello
We have a complete list of Javascript string methods, to check those please go through this Javascript String Complete reference article.