Home > Web Front-end > JS Tutorial > How Can I Pad a String to a Specific Length in JavaScript?

How Can I Pad a String to a Specific Length in JavaScript?

Linda Hamilton
Release: 2024-11-25 12:59:14
Original
778 people have browsed it

How Can I Pad a String to a Specific Length in JavaScript?

Pad a String to a Desired 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])
Copy after login

Example:

"Jonas".padStart(10); // Default pad string is a space
"42".padStart(6, "0"); // Pad with "0"
"*".padStart(8, "-/|\"); // produces '-/|\-/|*'
Copy after login

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;
};
Copy after login

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)
Copy after login

String Object Extension

Here's an extension to the String object:

String.prototype.paddingLeft = function (paddingValue) {
   return String(paddingValue + this).slice(-paddingValue.length);
};
Copy after login

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;
    });
};
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template