liveBook · Manning

String.prototype.padStart

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

A JavaScript string method that pads the start of a string with a specified filler until the string reaches a target length.

Need every binary IP octet to contain eight digits? String.prototype.padStart adds filler to the beginning of a string until it reaches a target length. If you omit the filler, it uses a space. section 6.2

Keep these behavior rules in mind:

  • The first argument is the target length; the second is the filler string. section 6.2
  • A multi-character filler repeats as needed, then is truncated if it cannot fit evenly. section 6.2
  • If the original string already meets or exceeds the target length, it is returned without padding. section 6.2

Pad binary octets

Number(octet).toString(2).padStart(8, '0') converts an octet to binary, then adds leading zeros to reach eight characters. For example, the binary value 10 becomes 00000010. Applying this to each octet produces a consistently padded binary IP address. section 6.2

function binaryIP(decimalIPStr) {
  return decimalIPStr.split('.').map(function(octet) {
    return Number(octet).toString(2).padStart(8, '0')
  }).join('.');
}

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

See padStart used in the complete binary IP conversion function. section 6.2

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

How deep it goes
Explains arguments, default filler, truncation, and behavior when the target is shorter than the string.
Examples
Demonstrates filler variations and padding binary IP octets with zeros.
What you can do after
Apply padStart to add leading filler and format binary IP octets to eight characters.
How it connects
Connects padStart with padEnd and repeat as string-padding alternatives.

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.