In this tutorial, I’ll go over several approaches to concatenate strings in JavaScript. There are various methods for manipulating strings in JavaScript. The concatenation of a string is a basic operation on a string in any programming language.
What is Concat Strings?
String concatenation in JavaScript is the process of combining two or more strings into a single string.
JavaScript Concat Strings
Let’s discuss the best ways to concatenate strings in JavaScript.
The Basics of String Concatenation
The most common approach is using the +
operator to concatenate two or more strings into a single string.
let firstName = "Adam"; let lastName = "Joe"; let fullName = firstName + " " + lastName; console.log(fullName);
The two strings firstName and lastName are combined into the fullName in the code above by using the +
operator.
Output:
Adam Joe
Concatenate String Using Template Literals
Expressions can be embedded within a string using template literals, which employ backticks (~). This is introduced in ES6, or ECMAScript 6.
let firstName = "Adam"; let lastName = "Joe"; let fullName = ${firstName} ${lastName}; console.log(fullName);
Output:
John Doe
The concat Method
Multiple strings can be concatenated using JavaScript’s concat method for strings. This function can take one or more parameters and merge them into a new string:
let str1 = "Adam"; let str2 = "Joe"; let greeting = str1.concat(str2); console.log(greeting);
in the above code, We have concatenated strings firstName and lastName using the concat()
method.
Output:
John Doe
Using join() method
The JavaScript join()
method is used to join all elements of an array into a string.
The basic syntax of the join()
method:
array.join(separator);
array
: The array whose elements will be joined into a string.separator (optional)
: A string is used to separate each element of the array. If not provided, a comma will be used as the default separator.
let words = ["Hi!", "I am", "Adam"]; let result = words.join(" "); console.log(result);
Output:
Hi, I am Adam
Conclusion:
We have discussed different approaches to solving string concatenation. You can use any of the techniques to do string concatenation using javascript. Whether you choose the traditional + operator, advanced template literals, concat method or join()
method.