Concatenate two strings in JavaScript
This post will discuss how to concatenate two strings in JavaScript.
There are several ways to concatenate two strings in JavaScript. Here are some of the most common functions, along with some examples and explanations:
1. Using + operator
One of the simplest ways to concatenate two strings in JavaScript is to use the + operator, which performs string concatenation if one of the operands is a string. Here’s an example:
|
1 2 3 4 5 6 7 8 |
let str1 = "Hello"; // A string variable let str2 = "World"; // Another string variable // Concatenate the strings with a space let result = str1 + " " + str2; // Prints "Hello World" console.log(result); |
We can also use the += operator, where x += y is a shorthand for x = x + y. Here’s an example:
|
1 2 3 4 5 6 7 8 9 10 11 |
// A string variable let str = "Hello"; // Concatenate a space to the string str += " "; // Concatenate another string to the string str += "World"; // Prints "Hello World" console.log(str); |
2. Using String.concat() function
Another way to concatenate two strings in JavaScript is to use the String.concat() function, which returns a new string that is the result of joining two or more strings. Here’s an example:
|
1 2 3 4 5 6 7 8 |
let str1 = "Hello"; // A string variable let str2 = "World"; // Another string variable // Concatenate the strings with a space using concat let result = str1.concat(" ", str2); // Prints "Hello World" console.log(result); |
However, using the + operator is less error prone in case the first operand is not a string.
3. Using Array.join() function
We can also use the Array.join() function, which returns a new string that is the result of joining all the elements in an array with a specified separator. Here’s an example:
|
1 2 3 4 5 6 7 8 |
// An array of strings let arr = ["Hello", "World"]; // Join the array elements with a space let result = arr.join(" "); // Prints "Hello World" console.log(result); |
This function is useful when we have an array of strings or when we want to specify a different separator between the strings.
4. Using template literals
This is a new feature in ES6 that allows us to create strings with embedded expressions and variables using backticks and placeholders. Template literals can also span multiple lines and support interpolation of any JavaScript expression. For example:
|
1 2 3 4 5 6 7 8 |
let str1 = "Hello"; // A string variable let str2 = "World"; // Another string variable // Concatenate the strings with template literals let result = `${str1} ${str2}`; // Prints "Hello World" console.log(result); |
That’s all about concatenating two strings in JavaScript.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)