JavaScript provides various methods to achieve specific string manipulation tasks. One such task is padding a string to a desired length, filling the empty spaces with characters. This article discusses different ways to pad a string in JavaScript.
ECMAScript 2017 (ES8) introduced the String.padStart method for this purpose. It takes two parameters: the desired length and an optional padding string (which defaults to a space).
"Jonas".padStart(10); // Default pad string is a space "42".padStart(6, "0"); // Pad with "0" "*".padStart(8, "-/|\"); // produces '-/|\-/|*'
If String.padStart is not supported in your JavaScript environment, you can add it as a polyfill:
if (!String.prototype.padStart) { String.prototype.padStart = function(length, padString) { padString = padString || " "; if (this.length >= length) return this; else return padString.repeat(length - this.length) + this; }; }
A simple way to pad a string is to concatenate it with the desired padding characters.
var n = 123 String("00000" + n).slice(-5); // returns 00123 ("00000" + n).slice(-5); // returns 00123 (" " + n).slice(-5); // returns " 123" (with two spaces)
You can also extend the String object to include a paddingLeft method for your convenience.
String.prototype.paddingLeft = function (paddingValue) { return String(paddingValue + this).slice(-paddingValue.length); };
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 code will return a time in the format "15:30".
The above is the detailed content of How Can I Pad Strings to a Desired Length in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!