Open In App

Which built-in method combines two strings and returns a new string in JavaScript ?

Last Updated : 09 Jan, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will know how to combine the text of two strings and return the new string. There are two best-fit methods for this situation:

We will explore both these methods & their implementations in detail & understand them through the examples.

Using concat() method: The concat() method is a built-in method that takes 2 or more strings as a parameter and returns the combination of all of the provided strings with the calling string, without changing the original strings.

Syntax:

str.concat(str 1, str 2, ... , str n);

Parameters: This method takes strings as arguments & joins them together to form a new string. The number of arguments to this method is equal to the number of strings to be joined together.

Example: This example describes getting the new string from combining more than two strings.

Javascript




let str1 = "Hello";
let str2 = "Geeks"
let returnedString = str1.concat(" ",
                     str2, "forGeeks", " ", "Learner");
console.log(returnedString);


Output:

Hello GeeksforGeeks Learner

Explanation: Here, we have used more than 2 strings to combine, the str1 is calling the concat() method so the provided parameter in sequence will be combined with the str1

Using join() method: This method takes an array as a caller object and returns the joined string in the same sequence as all elements that appeared in the array. This method doesn’t provide that much flexibility as compared to concat method.

Syntax:

array.join(separator);

Parameter: It is an optional parameter. The separator is the string or character which will be placed in between those elements of the array. By default, it is considered an empty string.

Return Value: It returns the string which contains the collection of array’s elements.

Example: This example describes the joining of the two strings by providing whitespace as a separator.

Javascript




let myStr1 = "Hello";
let myStr2 = "GFG Learner!";
const returnedString =
    [myStr1, myStr2].join(" ");
console.log(returnedString);


Output:

Hello GFG Learner!

Explanation: In the first and second lines, we have initialized two strings, & called the join() method by providing an array as a caller object which consists of those strings, and the whitespace(” “) as a separator. 

Note: We can also use the normal + operator or template strings to combine the strings in an efficient and simple way if there is no condition to return the new string after concatenation because these are not methods but normal language constructs.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads