DEV Community

M.Ark
M.Ark

Posted on

Concatenating Two or More Strings in JavaScript

Merging two or more strings into one
Concatenate the strings using the addition (+) operator:

var string1 = "This is a ";
var string2 = "test";
var string3 = string1 + string2; // creates a new string with "This is a test"

The addition operator (+) is typically used to add numbers together:
var newValue = 1 + 3; // result is 4
In JavaScript, the addition operator(+) is overloaded, meaning it can be used for multiple data types, including strings.
When used with strings, the results are concatenated, with the strings later in the equation appended to the end of the string result.
It can be used to add two strings:
var string3 = string1 + string2;
or you can add multiple strings:
var string1 = "This";
var string2 = "is";
var string3 = "a";
var string4 = "test";
var stringResult = string1 + " " + string2 + " " +
string3 + " " + string4; // result is "This is a test"

There is a shortcut to concatenating strings, and that’s the JavaScript shorthand assignment operator (+=).
var oldValue = "apples";
oldValue += " and oranges"; // string now has "apples and oranges"

is equivalent to:
var oldValue = "apples";
oldValue = oldValue + " and oranges";

The shorthand assignment operator works with strings by concatenating the string on the right side of the operator to the end of the string on the left.
There is a built-in String method that can concatenate multiple strings: concat. It takes one or more string parameters, each of which are appended to the end of the string
object:
var nwStrng = "".concat("This ","is ","a ","string"); // returns "This is a string"
The concat method can be a simpler way to generate a string from multiple values, such as generating a string from several form fields. However, the use of the addition operator is the more commonly used approach.

Top comments (0)