[ Web Proxy ]
URL:
Viewing: https://www.javascripttutorial.net/javascript-string-concat/ [Back]  [Original]

JavaScript String Concat() Method
Skip to content

String.prototype.concat()

Summary: in this tutorial, you’ll learn how to use the JavaScript concat() method to concatenate strings.

Introduction to the JavaScript String concat() method

The String.prototype.concat() method accepts a list of strings and returns a new string that contains the combined strings:

string.concat(str1, [...strN]);Code language: JavaScript (javascript)

If the arguments are not strings, the concat() converts them to strings before carrying the concatenation.

It’s recommended that you use the + or += operator for string concatenation to get better performance.

JavaScript String concat() examples

Let’s take some examples of using the concat() method.

1) Concatenating strings

The following example uses the concat() method to concatenate strings:

let greeting = 'Hi';
let message = greeting.concat(' ', 'John');

console.log(message);Code language: JavaScript (javascript)

Output:

Hi JohnCode language: JavaScript (javascript)

2) Concatenating an array of strings

The following example uses the concat() method to concatenate strings in an array:

let colors = ['Blue',' ','Green',' ','Teal'];
let result = ''.concat(...colors);

console.log(result);Code language: JavaScript (javascript)

Output:

Blue Green TealCode language: JavaScript (javascript)

Note that the ... before the colors array argument is the spread operator that unpacks elements of an array.

3) Concatenating non-string arguments

This example concatenates numbers into a string:

let str = ''.concat(1,2,3);

console.log(str);Code language: JavaScript (javascript)

Output:

123Code language: JavaScript (javascript)

In this example, the concat() method converts the numbers 1, 2, and 3 to the strings before concatenating.

Summary

Was this tutorial helpful ?
Yes No
Search …:

Searching

Trimming

Padding

Extracting

Concatenating

Replacing

Copyright © 2009 - Present by JavaScript Tutorial Website. All Right Reserved.


Web Proxy Viewer  |  New URL  |  Original Page