liveBook · Manning

String.prototype.repeat

As explained in Get Programming with JavaScript Next: New features of ECMAScript 2015, 2016, and beyond

A JavaScript string method that returns a new string consisting of the original string repeated a specified number of times.

Need to repeat a string a fixed number of times? String.prototype.repeat returns a string containing the original string repeated for the specified count. A fractional count is floored, so 4.9 repeats four times. section 6.2

A few quick checks:

One practical use is padding binary IP address octets with zeros. Convert each decimal octet to binary, then repeat '0' enough times to bring the result to eight characters and prepend those zeros. section 6.2

function binaryIP(decimalIPStr) {
  return decimalIPStr.split('.').map(function(octet) {
    let bin = Number(octet).toString(2);
    return '0'.repeat(8 - bin.length) + bin;
  }).join('.');
}

binaryIP('192.168.2.1');     1
!@%STYLE%@!
{"css":"{\"css\": \"font-weight: bold;\"}","target":"[[{\"line\":7,\"ch\":10},{\"line\":7,\"ch\":11}]]"}
!@%STYLE%@!

This implementation repeats zeros to make each converted octet eight characters long. section 6.2

How Get Programming with JavaScript Next: New features of ECMAScript 2015, 2016, and beyond covers it

How deep it goes
Explains string repetition and fractional-count flooring through examples and a practical padding function.
Examples
Shows repeated X and foo strings, plus zero-padding binary octets in an IP address conversion.
What you can do after
Apply String.prototype.repeat to build repeated strings and pad binary IP octets with zeros.
How it connects
Connects string repetition with binary number conversion and contrasts it with padStart and padEnd for padding.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Get Programming with JavaScript Next: New features of ECMAScript 2015, 2016, and beyond. The section links point to the parts of the book it draws on.