Skip to content

JavaScript Join two strings | Example of concat() and operator

  • by

There are many ways to Join two strings in JavaScript, like the operator and concat() method. Mostly The concat() method is used to join two or more strings.

JavaScript Join two strings Ways

  • + operator.
  • += operator
  • 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>  

Output:

JavaScript Join two strings

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>  

Output:

JavaScript Join two strings Example of concat

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

Leave a Reply

Your email address will not be published. Required fields are marked *