JS: String.prototype.padStart

By Xah Lee. Date: . Last updated: .

(new in ECMAScript 2017)

str.padStart(n)
  • Add spaces in front so the length is n.
  • Return the new string.
"x".padStart(3) === "  x"
str.padStart(n, padstr)

Use padStr to pad.

console.log("x".padStart(3, "0") === "00x");
console.log("x".padStart(4, "ab") === "abax");
console.log("x".padStart(5, "aabbcc"));
// aabbx

Example. beware of unicode.

/* no padding happens, because it is already length 2 */
console.log("🦋".padStart(2, "x") === "🦋");

/*
🦋
Name: BUTTERFLY
ID 129419
HEXD 1F98B
UTF8  F0 9F A6 8B
UTF16 D83E DD8B
*/

🛑 WARNING: string methods do not work the way you think if it contains characters outside of Unicode Basic Multilingual Plane (e.g. emoji 🦋.). See JS: String Index Code Unit

JS String.prototype