JS: String.prototype.padStart
(new in ECMAScript 2017)
str.padStart(n)-
- Add spaces in front so the length is n.
- Return the new string.
console.assert("x".padStart(3) === " x"); str.padStart(n, padstr)-
Use padStr to pad.
console.assert("x".padStart(3, "0") === "00x"); console.assert("x".padStart(4, "ab") === "abax"); console.assert("x".padStart(5, "aabbcc") === "aabbx");
Emoji in string
🛑 warning: if string contains a character outside of Basic Multilingual Plane (such as most emoji 🦋 or rarely used Chinese character), result of string methods may be unexpected. See JS: String Index and Code Unit.
/* no padding happens, because it is already length 2 */ console.assert( "🦋".padStart(2, "x") === "🦋", ); /* 🦋 Name: BUTTERFLY Codepoint: 129419 HEXD: 1F98B UTF8: F0 9F A6 8B UTF16: D83E DD8B */