Skip to content

JavaScript String concat() | Method

  • by

JavaScript String concat() Method used to join two or more strings. It does not change the given strings and returns a new string.

concat(str1)
concat(str1, str2)
concat(str1, str2, ... , strN)

JavaScript String concat()

Simple example code concat 2 string with space and comma.

<!DOCTYPE html>
<html>
<body>
  <script>
    const str1 = 'Hello';
    const str2 = 'World';

    console.log(str1.concat(' ', str2));

    console.log(str2.concat(', ', str1));

  </script>
</body>
</html>

Output:

JavaScript String concat()

More example Using concat()

let hello = 'Hello, '
console.log(hello.concat('Kevin', '. Have a nice day.'))
// Hello, Kevin. Have a nice day.

let greetList = ['Hello', ' ', 'Venkat', '!']
"".concat(...greetList)  // "Hello Venkat!"

"".concat({})    // [object Object]
"".concat([])    // ""
"".concat(null)  // "null"
"".concat(true)  // "true"
"".concat(4, 5)  // "45"

How to append or concat strings in JavaScript?

Answer: Use the + operator to concatenate two strings. same as you use for adding two numbers can be used. You can also use +=, where a += b is a shorthand for a = a + b. If the left-hand side of the + operator is a string, JavaScript will coerce the right-hand side to a string.

const str = 'Hello' + ' ' + 'World';
str; // 'Hello World'

Or

let str = 'Hello';
str += ' ';
str += 'World';
str; // 'Hello World'

Do comment if you have any doubts or suggestions on this Js concat() function code.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading