Sometimes, we want to create a string of variable length filled with a repeated character in JavaScript.
In this article, we’ll look at ways to create such strings with JavaScript.
Using the Array Constructor and the Arra.prototype.join Method
We can create an array with the Array
constructor.
Then we can call join
to join the array entries into a string with the given character as the separator.
For instance, we can write:
const len = 10
const character = 'a'
const str = new Array(len + 1).join(character);
console.log(str)
We create an Array
with length len + 1
.
Then we call join
with the character
that we want to repeat.
Therefore, str
is 'aaaaaaaaaa’
.
Use the String.prototype.repeat Method
Another way to create a string of variable length with a repeated character is to use the string’s repeat
method.
For instance, we can write:
const len = 10
const character = 'a'
const str = character.repeat(len);
console.log(str)
Then we get the same result as before.
Use a for Loop
We can also use a for
loop to concatenate the same character to a string until it reaches the given length.
To do this, we write:
const len = 10
const character = 'a'
let str = ''
for (let i = 1; i <= len; i++) {
str += character;
}
console.log(str)
We have a for
loop that starts with index variable 1 and stops when it reaches len
.
In the loop body, we concatenate the character
to str
.
And so we get the same result as before.
Conclusion
We can create a string that has a variable length with content consisting of a repeated character by using array methods, string methods, or loops.