4 different ways to Join two Strings in JavaScript
In this tutorial, we are going to learn about 4 different ways to join two (or more) strings in JavaScript.
First way: plus operator
We can use the plus +
operator to join one string with another string.
Here is an example:
const first = "Hello";
const second = "Pack";
const join = first + second;
console.log(join); // "HelloPack"
Second way: Es6 Template literals
In es6, the template literals provide us a string interpolation feature by using that we can join strings.
const first = "Hello";
const second = "Pack";
const join = `${first} ${second}`;
console.log(join); // "Hello Pack"
Third way : += operator
The +=
operator helps us to combine the second string with a first-string or vice versa instead of creating a third variable.
let first = "Hello";
let second = "Pack";
second += first; // combined second with first
console.log(second); // "Pack Hello"
Note: while using += operator your variables should be declared with
let or var
.
Fourth way : concat() method
The concat method accepts the string
as an argument and returns the new string by concatenating existing string with an argument.
Example:
const first = "Hello";
const greet = first.concat(", Wonderful People");
console.log(greet); // "Hello, Wonderful People"
Note: The concat( ) method doesn’t modify or change the existing string.
We can also concatenate more than one string by passing multiple arguments to the concat method.
const first = "Hello";
const greet = first.concat(" World!", " Keep laughing ");
console.log(greet); // "Hello World! Keep laughing "