Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to add two strings with a space in first string in JavaScript?
To concatenate two strings in JavaScript, we use the '+' operator. When the first string already contains a trailing space, we can directly concatenate without adding an explicit space. However, if there's no space, we need to add one manually between the strings.
Method 1: First String Has Trailing Space
When the first string already ends with a space, simple concatenation is sufficient:
<html>
<body>
<script>
function concatenateStrings(str1, str2) {
return (str1 + str2);
}
document.write(concatenateStrings("Hello World ", "from JavaScript"));
</script>
</body>
</html>
Hello World from JavaScript
Method 2: Adding Space Between Strings
When neither string has a trailing/leading space, we explicitly add a space character:
<html>
<body>
<script>
function concatenateWithSpace(str1, str2) {
return (str1 + " " + str2);
}
document.write(concatenateWithSpace("Hello World", "from JavaScript"));
</script>
</body>
</html>
Hello World from JavaScript
Alternative Methods
JavaScript provides other ways to join strings with spaces:
<html>
<body>
<script>
let str1 = "JavaScript";
let str2 = "Tutorial";
// Using template literals
let result1 = `${str1} ${str2}`;
document.write("Template literal: " + result1 + "<br>");
// Using join method
let result2 = [str1, str2].join(" ");
document.write("Array join: " + result2 + "<br>");
// Using concat method
let result3 = str1.concat(" ", str2);
document.write("Concat method: " + result3);
</script>
</body>
</html>
Template literal: JavaScript Tutorial Array join: JavaScript Tutorial Concat method: JavaScript Tutorial
Comparison
| Method | Best Use Case | Performance |
|---|---|---|
| + operator | Simple concatenation | Fast |
| Template literals | Complex string formatting | Fast |
| Array.join() | Multiple strings | Good for many strings |
| concat() | Method chaining | Slightly slower |
Conclusion
Use the + operator for simple string concatenation with spaces. Template literals offer cleaner syntax for complex string formatting, while array.join() is efficient for combining multiple strings.
Advertisements
