EN
JavaScript - String concat() method example
6 points
Concat method is used to join two or more strings in JavaScript. The method appends passed arguments to right side of string.
xxxxxxxxxx
1
var a = 'abc';
2
var b = '123';
3
4
console.log( a.concat() ); // abc
5
console.log( a.concat(b) ); // abc123
6
console.log( b.concat(a) ); // 123abc
Syntax | String.prototype.concat([string2[, string3[, ..., stringN]]]) |
Parameters | string2...stringN - optional string type agruments (primitive value). |
Result |
Combining the string on which the function was called and arguments of the string type (primitive values). Further arguments to the function are appended on the right. If no arguments passed it returns same string. |
Description | concat takes zero or more arguments and returns containing the text of the combined strings. |
Note: it is strongly recommended to use
+=
operator insteadconcat()
method to get better peformance of operations.
xxxxxxxxxx
1
var text = '_abc';
2
3
text += '_123';
4
text += '_ABC';
5
text += '_000';
6
7
console.log(text);
In this section presented program execution time depends of JavaScript implementation.
Note: some browsers can be optimized with
concat()
method.
xxxxxxxxxx
1
var text1 = 'abc1';
2
var text2 = 'abc1';
3
4
var texts = [
5
'abc2', 'abc3', 'abc4'
6
];
7
8
// -----------------------------------------------
9
// += operator test
10
11
var t1 = new Date();
12
13
for (var i = 0; i < 100000; ++i) {
14
text1 += texts[i % texts.length];
15
}
16
17
var t2 = new Date();
18
var dt = t2 - t1;
19
20
console.log(dt + 'ms <- += operator test time');
21
22
// -----------------------------------------------
23
// concat method test
24
25
var t1 = new Date();
26
27
for (var i = 0; i < 100000; ++i) {
28
text2 = text2.concat(texts[i % texts.length]);
29
}
30
31
var t2 = new Date();
32
var dt = t2 - t1;
33
34
console.log(dt + 'ms <- concat method test time');