How to concatenate string in javascript . Every programming language provides ways to concatenate one or more string . Facility to concatenate one or more string is very useful if you are working on web application .
In this post, we learn various ways to concatenate string in javascript.
How to Concatenate String in Javascript
Method 1 : Using + Operator
Simple and easiest way to concatenate one or more strings is through +(addition) operator.
1 2 3 4 5 6 7 8 9 10 11 |
var first="concatenate "; var second="my "; var third="string"; var str = first + " "+second+" "+third; /* Output : concatenate my string */ console.log(str); |
Difference between document.ready and window.onload
Method 2: Using += Operator
1 2 3 4 5 6 7 |
var str = "concatenate"; str += " my"; str += " string"; /* Output: "concatenate my string" */ console.log(str); |
Method 3: Using Javascript concat() method.
1 2 3 4 5 6 7 |
/* Concatenate second and third string to first. */ var str = first.concat(second,third); /* Output: concatenate my string */ console.log(str); |
Convert an array to string using javascript join() method
If you have an array and want to print as a string then use join() method.
1 2 3 4 5 |
var str = ["concatenate", "my", "string"]; /* Output : concatenate my string */ console.log(str.join(" ")); |
Difference between undefined and null value
Conclusion
I have demostrated various methods to concatenate string in javascript. Here is the performance analysis for various concatenation operation.
If i miss any points, let us know through comments.