How to join two strings in JavaScript
We’ll show you how to join two strings in JavaScript today.
A string can be assigned to a variable and then combined with another string. With this tutorial, we’ll teach you how to connect two or more strings in JavaScript.
Let’s say we have a first and last name and want to combine them so we can use JavaScript to combine two strings and generate a whole name.
- How to remove the first item from an array in JavaScript
- How to Copy to Clipboard in JavaScript
- Restrict or Disable browser back button using JavaScript
- JavaScript Convert 12 Hour AM/PM Time to 24 Hour Time Format
1. Using + operator
The + operator can be used to create a new string or to add to an existing string.
const firstname = 'Code';
const lastname = 'Premix';
const fullname = firstname + ' ' + lastname;
console.log(fullname);
// Output: Code Premix
We have merged the strings that are assigned to the variable in the above code. We’ll now connect the variable to another string.
const firstname = 'Code';
const lastname = 'Premix';
const newStr = 'Welcome to ' + firstname + ' ' + lastname + '!';
console.log(newStr);
// Output: Welcome to Code Premix!
As shown below, attach the variable to an existing string using +=.
const firstname = 'Code';
const lastname = 'Premix';
let newStr = 'Welcome to our website';
newStr += ' ' + firstname + lastname;
console.log(newStr);
// Output: Welcome to our website CodePremix
2. Template string
When concatenating strings using the + operator, it’s usual to lose a space. You may use template string to add interpolate variables to a string in JavaScript, as shown below.
const firstname = 'Code';
const lastname = 'Premix';
let newStr = `Welcome to our website ${firstname} ${lastname}.`;
console.log(newStr);
// Output: Welcome to our website Code Premix!
3. concat() method
We may connect two or more strings using Javascript’s built-in concat()
technique.
The concat() function does not modify existing strings and instead returns a new string that is created by joining the string parameters to the original string.
Syntax
string.concat(str1, str2, ... strN);
Example
const str = 'Welcome';
const result = str.concat(' to',' our',' website', ' codepremix.com');
console.log(result);
// Output: Welcome to our website codepremix.com
4. join() method
Finally, the join()
function concatenates all of the array’s elements and returns 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
array.join(separator);
Example
const str1 = ['Welcome','to','our','website', 'codepremix.com'].join(' ');
console.log(str1);
// Output: Welcome to our website codepremix.com
const str2 = ['a','b','c'].join('|');
console.log(str2);
// Output: a|b|c
I hope you have found this post to be informative.
Thank you for reading. Happy Coding..!!