- concat() method
Examples of Join two strings in JS
Let’s see the one one example of each ways.
1. + operator
Let’s see you have 2 string name and last_name, then you can assign those to the
fullname variable like this:
<!DOCTYPE html> <html> <body> <script> var name = "John" var last_name = "Walk" const fullname = name + last_name alert(fullname) </script> </body> </html>
2. += operator
In this way you don’t needed to instantiate a new variable, see below example how to use the
+= operator to add the second string to the first:
<!DOCTYPE html> <html> <body> <script> var name = "John" var last_name = "Walk" name += last_name alert(name) </script> </body> </html>
3. concat() method
This method does not change the existing strings, but returns a new string containing the text of the joined strings.
<!DOCTYPE html> <html> <body> <script> var str1 = "Hello "; var str2 = "world!"; var res = str1.concat(str2); alert(res) </script> </body> </html>
Do comment if you have any questions and suggestions on this tutorial.
Note: The All JS Examples codes are tested on the Safari browser (Version 12.0.2) and Chrome.
OS: macOS 10.14 Mojave
Code: HTML 5 Version
Degree in Computer Science and Engineer: App Developer and has multiple Programming languages experience. Enthusiasm for technology & like learning technical.