For example, if we have a large dataset related to the details of students then it becomes difficult to collect the data of a single student with different features. Therefore, we use a concatenation method to combine the data of a student in a single string like first name, last name, id number, etc.
In the following tutorial, we are going to describe the concatenation methods in JavaScript. Three types of concatenation methods are used in JavaScript.
Let’s walk through each method and have a better understanding.
Concat() method
JavaScript provides a built-in concat() method to merge two or more strings.In this method, two or more values from the calling string are merged and returned to a new concatenated string. This function takes two strings and returns a new concatenated string.
Syntax
- All parameters should be in string form, before the implementation of concatenation operation.
- This method will not change the original input value of strings.
Example
var sr2 = "Javascript ";
var sr3 = "String Concatenation";
var res = sr1.concat(sr2, sr3);
console.log(res);
//Output: Example of Javascript String Concatenation
+ operator for concatenation
We can also add two strings like we add two numbers by using the “+” operator because in JavaScript + operator is also used for concatenation.
Example
let str4 = 'Friends';
result = str + str4
//Output: Best Friends
Not even this, you can also concatenate strings by using shorthand += operator.
str += ' ';
str += 'Friends';
//Output: Best Friends
Output
Template Literal
In JavaScript, template literals are defined with “ backticks. These literals allow the expressions in the embedded form. In template literal, Interpolation and multi-line and string features can be used. The syntax of the template literal is given below:
console.log(`i have a ${pet}.`);
In the above code, we have binded the variable “pet” inside the template literals.
Another example of the template literal for string concatenation is given below, where we are merging three strings using template literals:
let str2 = 'Example in';
let str3 = 'JavaScript';
let strJoined = `${str1} ${str2} ${str3}`;
console.log(strJoined);
//Output: String Concatenation Example in JavaScript
THis is how you can concatenate strings in javaScript using template literals.
Conclusion
To concatenate strings, javascript provides three different ways, the first is concat() method which takes strings as an argument, the second way is to use “+” operator for combining two or more strings and third is to use template literals for writing long strings along with the variable bindings. In this tutorial, we describe the concatenation methods to merge strings in JavaScript along with examples.