How to add two strings with a space in first string in JavaScript?


To add two strings we need a '+' operator to create some space between the strings, but when the first string itself has a space with in it, there is no need to assign space explicitly. 

In the following example since the string 'str1' has a space with in it, just only concatenation without space is adequate to add both the strings.

Example

Live Demo

<html>
<body>
   <script>
      function str(str1, str2) {
         return (str1 + str2);
      }
      document.write(str("tutorix is the best ","e-learning platform"));
   </script>
</body>
</html>

Output

tutorix is the best e-learning platform

In case if there is no space exist in first string then we have to create space(" ") and join the two strings as shown below. 

Example

Live Demo

<html>
<body>
   <script>
      function str(str1, str2) {
         return (str1 + " " + str2);
      }
      document.write(str("tutorix is the best","e-learning platform"));
   </script>
</body>
</html>

Output

tutorix is the best e-learning platform

Updated on: 29-Jun-2020

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements