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
How to concatenate the string value length -1 in JavaScript.
In JavaScript, you can concatenate a string value (length-1) times using the Array() constructor with join(). This technique creates an array with empty elements and joins them with your desired string.
Syntax
new Array(count).join('string')
Where count is the number of times you want to repeat the string, and the actual repetitions will be count - 1.
How It Works
When you create new Array(5), it generates an array with 5 empty slots. The join() method places the specified string between each element, resulting in 4 concatenated strings (length-1).
Example
var count = 5;
var values = new Array(count + 1).join('John');
console.log("Array(6).join('John'):", values);
console.log("Length:", values.length);
var count1 = 5;
var values1 = new Array(count1).join('John');
console.log("Array(5).join('John'):", values1);
console.log("Length:", values1.length);
Array(6).join('John'): JohnJohnJohnJohnJohn
Length: 25
Array(5).join('John'): JohnJohnJohnJohn
Length: 20
Alternative Methods
You can also use the repeat() method for cleaner syntax:
var count = 5;
var values = 'John'.repeat(count);
console.log("Using repeat():", values);
// Compare with Array join approach
var valuesArray = new Array(count + 1).join('John');
console.log("Using Array join:", valuesArray);
console.log("Same result:", values === valuesArray);
Using repeat(): JohnJohnJohnJohnJohn Using Array join: JohnJohnJohnJohnJohn Same result: true
Comparison
| Method | Syntax | Browser Support |
|---|---|---|
Array().join() |
new Array(n).join('str') |
All browsers |
String.repeat() |
'str'.repeat(n) |
ES6+ (newer) |
Conclusion
Use new Array(count).join('string') to concatenate a string (count-1) times. For modern environments, String.repeat() provides a cleaner alternative.
