Home > Article > Web Front-end > How Can I Pad a String to a Specific Length in JavaScript?
Introduction
Adding padding to a string can be a necessary task for various reasons, such as alignment or formatting. This article explores how to pad a string to a specified length in JavaScript.
ES8 Solution
ECMAScript 2017 (ES8) introduced String.padStart, making string padding effortless. Its syntax is:
string.padStart(targetLength, [padString])
Example:
"Jonas".padStart(10); // Default pad string is a space "42".padStart(6, "0"); // Pad with "0" "*".padStart(8, "-/|\"); // produces '-/|\-/|*'
Polyfill for Pre-ES8 Browsers
For browsers that don't support ES8, a polyfill can be used:
String.prototype.padStart = function (targetLength, padString) { if (this.length >= targetLength) { return this; } padString = padString !== undefined ? padString : ' '; return padString.repeat((targetLength - this.length) / padString.length) + this; };
Classical Solution
Before ES8, a common approach involved prepending padding:
var n = 123 String("00000" + n).slice(-5); // returns 00123 ("00000" + n).slice(-5); // returns 00123 (" " + n).slice(-5); // returns " 123" (with two spaces)
String Object Extension
Here's an extension to the String object:
String.prototype.paddingLeft = function (paddingValue) { return String(paddingValue + this).slice(-paddingValue.length); };
Usage Example:
function getFormattedTime(date) { var hours = date.getHours(); var minutes = date.getMinutes(); hours = hours.toString().paddingLeft("00"); minutes = minutes.toString().paddingLeft("00"); return "{0}:{1}".format(hours, minutes); }; String.prototype.format = function () { var args = arguments; return this.replace(/{(\d+)}/g, function (match, number) { return typeof args[number] != 'undefined' ? args[number] : match; }); };
This returns a time in the format "15:30".
The above is the detailed content of How Can I Pad a String to a Specific Length in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!