How to combine two strings in JavaScript
Today, we’ll explain to you how to combine two strings in JavaScript.
We can assign a string to a variable and combine the variable with another string. Here, we will show you the different ways to join two or more strings in JavaScript.
Suppose, we have a first name and last name and want to join both names so we can join two strings and create a full name using JavaScript.
Different ways to concatenate strings in JavaScript
1. Using + operator
We can use the + operator to create a new string or change the existing string by adding it.
1 2 3 4 5 | const firstname = 'Clue'; const lastname = 'Mediator'; const fullname = firstname + ' ' + lastname; console.log(fullname); // Output: Clue Mediator |
In the above code, we have combined the strings which is assigned to the variable. Now, we will join the variable to another string.
1 2 3 4 5 | const firstname = 'Clue'; const lastname = 'Mediator'; const newStr = 'Welcome to ' + firstname + ' ' + lastname + '!'; console.log(newStr); // Output: Welcome to Clue Mediator! |
Also, append the variable to an existing string using += as shown below.
1 2 3 4 5 6 | const firstname = 'Clue'; const lastname = 'Mediator'; let newStr = 'Welcome to our website'; newStr += ' ' + firstname + lastname; console.log(newStr); // Output: Welcome to our website ClueMediator |
2. Template string
It’s a common issue to missing space when concatenating strings using + operator. In JavaScript, you can add interpolate variables into string using template string as shown below.
1 2 3 4 5 | const firstname = 'Clue'; const lastname = 'Mediator'; let newStr = `Welcome to our website ${firstname} ${lastname}.`; console.log(newStr); // Output: Welcome to our website Clue Mediator! |
3. concat() method
Using Javascript built-in concat()
method, we can join two or more strings.
The concat() method does not change the existing strings and returns a new string that results from concatenates the string arguments to the original string.
Syntax
1 | string.concat(str1, str2, ... strN); |
Example
1 2 3 4 | const str = 'Welcome'; const result = str.concat(' to',' our',' website', ' cluemediator.com'); console.log(result); // Output: Welcome to our website cluemediator.com |
4. join() method
At last, the join()
method concatenates all elements of the array and return a string. The join()
method accepts an optional parameter called separator that separates the elements of the string. The default separator value is comma (,
).
Syntax
1 | array.join(separator); |
Example
1 2 3 4 5 6 7 | const str1 = ['Welcome','to','our','website', 'cluemediator.com'].join(' '); console.log(str1); // Output: Welcome to our website cluemediator.com const str2 = ['a','b','c'].join('|'); console.log(str2); // Output: a|b|c |
I hope you find this article is helpful.
Thank you for reading. Happy Coding..!! 🙂