Repeat a string in JavaScript
Beginner · 3 min read
Sometimes you need the same piece of text many times in a row: a line of dashes under a heading, spaces to indent nested items, stars for a rating. Writing them out by hand is error-prone, and a loop is more code than the job deserves. Strings have a method for it: repeat.
In this tutorial you will draw a thirty-character rule, build an indent three levels deep, and find out what repeat does with a fractional count and a negative one. You should know what a string and a number are.
What repeat does
text.repeat(count) returns a new string made of count copies of text, stuck together with nothing between them:
console.log('ab'.repeat(3)); // 'ababab'
Like every string method, it leaves the original string as it was.
Where it is used
A rule is a line of characters such as ------ used to separate parts of plain-text output. An indent is space at the start of a line that shows nesting, for example two spaces per level in a tree of folders. Both are "this character, this many times", which is exactly what repeat does.
Here is the exercise. Try it yourself first if you like, or read on and we will build it step by step.
32 Repeat a string
easyBuild a thirty-character horizontal rule and a three-level indent. Then ask repeat for a fractional count and a negative one.
Stuck? Three hints, smallest first
- 1.
repeat(n)returns n copies joined together, with no separator. - 2. A fractional count is truncated towards zero rather than rounded.
- 3. A negative count is an error, not an empty string.
Step 1: draw a rule
const rule = (width) => '-'.repeat(width);
console.log(rule(30)); // '------------------------------'
console.log(rule(30).length); // 30
One dash, thirty times. Wrapping it in a function means the width is easy to change.
Step 2: indent by level
const line = ' '.repeat(3) + 'deep';
console.log(line); // ' deep'
console.log(line.length); // 10
Two spaces per level, three levels, gives six spaces in front of the word. In a tree, the level would come from how deep the item is.
Step 3: zero and one
console.log('ab'.repeat(0)); // '' (an empty string)
console.log('ab'.repeat(1)); // 'ab'
console.log(''.repeat(100)); // '' (an empty string)
Zero copies is an empty string, which is handy: an item at level 0 gets no indent without any special code. One copy is the text itself. A hundred copies of nothing is still nothing.
Step 4: a fractional count
What if the count isn't a whole number?
console.log('ab'.repeat(2.9)); // 'abab'
You might expect it to round 2.9 up to 3. It doesn't: the fraction is cut off, so 2.9 becomes 2. This matters when the count comes from a division. To center a title in a width of 9 you might write ' '.repeat((9 - 4) / 2). (9 - 4) / 2 is 2.5, which becomes 2, so the title ends up one space short on one side.
Step 5: a negative count
try {
'ab'.repeat(-1);
} catch (e) {
console.log(e.constructor.name); // 'RangeError'
console.log(e.message); // 'Invalid count value: -1'
}
A negative count is not treated as zero. It throws a RangeError, an error that means "this number is outside the allowed range". If the count is worked out by subtraction, such as width - text.length, it can go negative when the text is longer than the width. Guard it with Math.max(0, count).
Step 6: repeat or padEnd?
padEnd from the padding exercise can sometimes do the same job:
console.log('x' + '.'.repeat(4)); // 'x....'
console.log('x'.padEnd(5, '.')); // 'x....'
Both give the same string. Choose the one that says what you mean. Use repeat when you know how many copies you want. Use padEnd when you know the total width the string should reach.
The full solution
Here is the complete answer: the rule, the indent, the fractional and negative counts, and the comparison with padEnd, each with a check. Press Run to see the rule and the two error cases.
const rule = (width) => '-'.repeat(width);
const negative = (() => {
try { return 'ab'.repeat(-1); } catch (e) { return e.constructor.name; }
})();
console.log(rule(30));
console.log("' '.repeat(3) + 'deep' :", JSON.stringify(' '.repeat(3) + 'deep'));
console.log("'ab'.repeat(2.9) :", 'ab'.repeat(2.9), '<- truncated, not rounded');
console.log("'ab'.repeat(-1) :", negative);
Output
10 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 10 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('repeat makes n copies', 'ab'.repeat(3), 'ababab');
test('zero copies is an empty string', 'ab'.repeat(0), '');
test('one copy is the string itself', 'ab'.repeat(1), 'ab');
test('a fractional count is truncated, not rounded', 'ab'.repeat(2.9), 'abab');
test('a negative count throws a RangeError', negative, 'RangeError');
test('a rule of the width asked for', rule(30).length, 30);
test('an indent of two spaces per level', ' '.repeat(3) + 'deep', ' deep');
test('repeating an empty string gives an empty string', ''.repeat(100), '');
test('repeat and padEnd overlap for simple filling', 'x' + '.'.repeat(4), 'x'.padEnd(5, '.'));
test('and the original is unchanged', (() => { const s = 'ab'; s.repeat(3); return s; })(), 'ab');
repeat(2.9) giving 'abab' follows the language's usual integer conversion, which truncates towards zero. That matters when the count came from a division: 'x'.repeat(width / 2) quietly rounds down on an odd width, and the column you were filling comes out one short.
Prefer padEnd when the goal is a total width and repeat when the goal is a count. They can express the same thing, but only one of them says what you meant.
Common mistakes
- Passing a negative count. It throws a
RangeError. UseMath.max(0, count)when the count is calculated. - Expecting a fraction to round.
repeat(2.9)gives two copies. Round on purpose withMath.roundif you need it. - Forgetting it returns a new string.
s.repeat(3);on its own line changes nothing. Keep the result.
Try it yourself
- Write
stars(rating)that returns'★★★☆☆'forstars(3)out of 5. - Print a box: a rule, the word
'Menu'between two|characters, and the rule again, all the same width. - Write
indent(text, level)that adds two spaces per level and returns the text unchanged for level 0.