String operators (JavaScript)
String operators concatenate values.
Operator | Description |
---|---|
string1 + string2 |
Concatenates string1 and string2 so
the beginning character of string2 follows the ending
character of string1 . |
string1 += string2 |
Concatenates string1 and string2 ,
and assigns the result to string1 . |
Usage
The plus operator means concatenation if either of the operands is a string. For example,"foo"
+ 5 + 1
means "foo51"
, while "foo"
+ (5 + 1)
means "foo6"
. Best practice is
to parenthesize non-string expressions within string expressions.Examples
This example concatenates two string variables.function p(stuff) {
print("<<<" + stuff + ">>>");
}
var f = "foo";
var b = "bar";
p(f + " " + b); // "foo bar"
This example concatenates two string variables and assigns the result to a variable.
function p(stuff) {
print("<<<" + stuff + ">>>");
}
var f = "foo";
var b = "bar";
var fb = f;
fb += " ";
fb += b;
p(fb); // "foo bar"
This example demonstrates how numeric
values are concatenated with strings.
function p(stuff) {
print("<<<" + stuff + ">>>");
}
var f = "foo";
var n = 5;
p(f + n); // foo5
p(5 + f); // 5foo
p(f + n + 1); // foo51
p(f + (n + 1)); // foo6