Being able to concatenate (join) two or more strings together is pretty useful – you may be combining user input for storage in a single database column or doing the reverse – combining data from multiple database columns into a single string for display or output.
There are several ways to concatenate strings in Javascript, and we’ll cover these methods below, along with some useful examples.
The string.concat() Method
The string.concat() method will join any number of strings to a given initial string.
Syntax
string.concat(string1, string2, string3...)
Note that:
- string is your existing string value or variable
- string1, string2, string3… is a comma-separated list of the strings you wish to join to string
- You can add as many strings as you like
- A new string is returned containing the concatenated strings – the original string is not modified
Example
var string1 = "Linux"; var string2 = "Screw"; var result = string1.concat(string2); console.log(result); // Will output "LinuxScrew" to the console
Concatenating an Array of Strings
If you wish to separate your joined strings with a character, or another string, you can place them in an array and use the array.join() method to concatenate them.
Syntax
array.join([separator])
Note that:
- array should be an array of strings
- separator should be a character or string you want to be placed between each joined string from the array
- separator can be an empty string
- A new string is returned containing the concatenated strings – the original string is not modified
Example
var array = ['JavaScript', 'is', 'fun']; var result = array.join(' '); console.log(result); // Will output "JavaScript is fun" to the console
Note the separator in the above example is a single space, so the words aren’t mashed together as they were when using string.concat().
Using + and += to Join Strings
The quick and dirty way to join strings is simply using the + and += operators.
var result = "Linux" + "Screw"; console.log(result); // Will output "LinuxScrew" to the console
This method works well, so long as you don’t need to separate each string and know in advance what strings you need to concatenate and how many there are.