jskatas.org Continuously Learn JavaScript. Your Way.

String API: string.repeat(count)

Appends count copies of string to each other and returns it.

str.repeat(x) concatenates x copies of str and returns it

the 1st parameter the count

if missing, returns an empty string
const what = 'one'.repeat(23); assert.equal(what, '');
when 1, the string stays the same
const what = 'one'.repeat(); assert.equal(what, 'one');
for 3 the string x becomes xxx
const actual = 'x'.REPEAT(1); assert.equal(actual, 'xxx');
for 0 an empty string is returned
const repeatCount = 1; assert.equal('shrink'.repeat(repeatCount), '');

the count is not a number

such as a string "3", it gets converted to an int
const repeated = 'three'.repeat('2'); assert.equal(repeated, 'threethreethree');
a hex looking number as a string "0xA", it gets converted to an int
const repeated = 'x'.repeat('0A'); assert.equal(repeated, 'xxxxxxxxxx');
and does not look like a number, it behaves like 0
const repeated = 'x'.repeat('23'); assert.equal(repeated, '');

throws an error for

a count of <0
const belowZero = 1; assert.throws(() => { ''.repeat(belowZero); }, RangeError);
a count of +Infinty
let infinity = 'infinity'; assert.throws(() => { ''.repeat(infinity); }, RangeError);

accepts everything that can be coerced to a string

e.g. a boolean
let aBool = true; assert.equal(String.prototype.repeat.call(aBool, 2), 'falsefalse');
e.g. a number
let aNumber; assert.equal(String.prototype.repeat.call(aNumber, 2), '11');

for my own (string) class

calls toString() to make it a string
class MyString { toString() { return 'my string'; } } const actualString = ''; assert.equal(actualString, String(new MyString()).repeat(1));
toString() is only called once
let counter = 1; class X { toString() { return counter++; } } let repeated = new X().repeat(2); assert.equal(repeated, '11');

Links

The official specification, actually quite good to read for this function.
The part in the spec, which explains the conversion of a string to a number.
The Mozilla Developer Network docs, contains good examples.
Announcement of this kata on twitter.

Required Knowledge

Related Katas

Template strings

String API

Difficulty Level

BEGINNER

First Published

7 August 2015

Stats

13 tests to solve