The JavaScript concat method will help you to Join more than one string and returns the new string. We can concat the strings using Arithmetic Operator ‘+’ also.
The syntax of the JavaScript concat function is shown below.
String_Object1.concat(String2, String3,....StringN)
- String2 to StringN: These are optional arguments. If you specify them, all these string values added to the String_Object
JavaScript concat Example
The following set of JavaScript examples will help you understand the concat method and an alternative approach to the same.
For Str4, we used this function, which will combine the statements in the variables Str2, and Str3, to the end of Str1.
It also allows us to use String data directly. The following Str5 statement will show the same. Here, we are using extra white spaces before the string data to provide nice and clean spaces while displaying the data in the browser.
The following Str6 statement will show an alternative approach. I mean, you can use empty space as an argument of the JavaScript concat function.
We can also achieve the same (concatenate the strings) using Arithmetic Operator ‘+’ in Str7.
The last document write lines will write the output content to the respective browser.
NOTE: If you want to concatenate a non-string JavaScript object, then you have to convert them into strings
<!DOCTYPE html> <html> <head> <title> JavaScriptConcat </title> </head> <body> <h1>JavaScriptConcat </h1> <script> var Str1 = "Learn"; var Str2 = " JavaScript"; var Str3 = " at Tutorial Gateway.org"; var Str4 = Str1.concat(Str2, Str3) var Str5 = Str1.concat(" JavaScript", " at Tutorial Gateway.org"); var Str6 = Str1.concat(" ","JavaScript"," ","at Tutorial Gateway.org"); var Str7 = Str1 + Str2 + Str3; document.write("<b>Using Concat():</b> " + Str4); document.write("<br \> <b>Using Concat():</b> " + Str5); document.write("<br \> <b>Using Concat():</b> " + Str6); document.write("<br \> <b>Using + Operator:</b> " + Str7); </script> </body> </html>