JavaScript String concat() Method
JavaScript concat() function is used to join two or more strings together without changing the original strings and returning a new string.
Syntax:
str.concat(string2, string3, string4,......, stringN)
Arguments: The arguments to this function are the strings that need to be joined together. The number of arguments to this function is equal to the number of strings to be joined together
Return value: This function returns a new string that is the combination of all the different strings passed to it as the argument.
Below is an example of the concat() Method.
Example:
JavaScript
<script> // JavaScript to illustrate concat() function function func() { // Original string var str = 'Geeks' ; // Joining the strings together var value = str.concat( ' for' , ' Geeks' ); console.log(value); } func(); </script> |
Output:
Geeks for Geeks
An example of the above function is provided below:
Example 1:
print('It'.concat(' is',' a',' great',' day.'));
Output:
It is a great day.
In this example, the function concat() joins together “It” with ” is”, ” a”, ” great”, “day.” to create a final string containing all the strings.
The code for the above function is provided below:
Example 1:
JavaScript
<script> // JavaScript to illustrate concat() function function func() { // Original string var str = 'It' ; // Joining the strings together var value = str.concat( ' is' , ' a' , ' great' , ' day.' ); console.log(value); } func(); </script> |
Output:
It is a great day.
The concat() function can also be used to concat strings stored in two or more variables. Also, spaces can also be added to the strings using the concat() function.
Example 2: In this example, we will see the concatenation of two strings stored in different variables also we will see how to include spaces between the strings.
Javascript
<script> let str1 = 'Geeks' let str2 = 'For' let str3 = 'Geeks' // Concating all the strings together without spaces let result1 = str1.concat(str2,str3) console.log( 'Result without spaces: ' +result1) // Concating all the strings together with spaces let result2 = str1.concat( ' ' ,str2, ' ' ,str3) console.log( 'Result with spaces: ' +result2) </script> |
Output:
Result without spaces: GeeksForGeeks Result with spaces: Geeks For Geeks
Supported Browsers:
- Chrome 1 and above
- Edge 12 and above
- Firefox 1 and above
- Internet Explorer 4 and above
- Opera 4 and above
- Safari 1 and above
Please Login to comment...