The concat()
method of the String class in JavaScript concatenates a list of strings to a provided string.
The process is illustrated below:
The prototype of the concat()
method is shown below:
string.concat(str1, str2, ... , strN);
In the command shown above, string
represents any string object.
The concat()
method accepts one or more strings as parameters. There is no limit to the number of strings that can be provided in the parameter list.
The concat()
method returns the newly created string by concatenating the strings provided as parameters with the string used to invoke the method.
The code below shows how the concat()
method can be used in JavaScript:
// initialize stringsvar stringOne = "Learning ";var stringTwo = "the Javascript String library ";var stringThree = "with Educative";// create new concatenated stringvar concatString = stringOne.concat(stringTwo, stringThree, "!");// print stringconsole.log(concatString);
First, three string objects are initialized. A space is left at the end of the strings to allow for separation between the string snippets in the concatenated string.
The concat()
method in line takes the argument list and concatenates all the provided strings to stringOne
. You need to ensure that you provide the space characters between the different strings, since the concat()
method does not add spaces automatically.
Note: You can also use assignment operators, e.g.,
+
and+=
, to concatenate strings instead of theconcat()
method.
Free Resources