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:
- 'X'.repeat(4) produces 'XXXX'. section 6.2
- 'foo'.repeat(3) produces 'foofoofoo'. section 6.2
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
