Search this site...

Concatenating strings with the + operator

The most common operations performed with strings is concatenation. Concatenation is a process of combining two strings into one longer string. For example, we could combine the strings "Scripting" and "Master" into a new string as "Scripting Master."

So what JavaScript operator do you use to concatenate a string? Well, you will use the "+" operator. Note this symbol is also used as a mathematical addition operator in JavaScript. So if you are using the "+" with numerical values it will add the two values; if you use the same operator with two strings, it will concatenate (combine into one) two strings.

The following shows a simple example:

<script language="javascript">
var string1, string2, stringConcatenated;
string1 = "Concatenating "; // first string
string2 = "strings"; // second string
stringConcatenated = string1 + string2; // Concatenating strings
document.write (stringConcatenated); // printing the Concatenated string
</script>

In the above example, we use three string variables. Remember a string is surrounded by either single or double quotation marks. On line 5, stringConcatenated = string1 + string2;, we use the "+" operator to concatenate two strings. Before the concatenation, we had two strings: "Concatenating " and "strings." After the concatenation, we end up with a combined longer string: "Concatenating strings." The following verifies our output of the JavaScript code:

The following shows a more complex example of the concatenate operator:

<script language="javascript">
var strOut;
strOut = "<table width='300' border='1' cellspacing='0' cellpadding='3'>";
strOut = strOut + "<tr>";
strOut = strOut + "<th colspan='2'>The + operator in JavaScript</th>";
strOut = strOut + "</tr>";
strOut = strOut + "<tr>";
strOut = strOut + "<th>When used in</th>";
strOut = strOut + "<th>Performs</th>";
strOut = strOut + "</tr>";
strOut = strOut + "<tr>";
strOut = strOut + "<td>Mathematical expression</td>";
strOut = strOut + "<td>Addition</td>";
strOut = strOut + "</tr>";
strOut = strOut + "<tr>";
strOut = strOut + "<td>String expression</td>";
strOut = strOut + "<td>Concatenation</td>";
strOut = strOut + "</tr>";
strOut = strOut + "</table>";
document.write (strOut);
</script>

In this example, we use just one variable named strOut. One line 3, we assign a complex string to this variable. Notice we are using single quotes for attribute values of a table tag. Then, on line 4 we concatenate the string "<tr>" with the string "<table width='300' border='1' cellspacing='0' cellpadding='3'>" and results in:

<table width='300' border='1' cellspacing='0' cellpadding='3'>
<tr>

Similarly, we concatenate more strings, one at a time, to this string, and end up creating a table that looks like:

The + operator in JavaScript
When used in Performs
Mathematical expression Addition
String expression Concatenation