阿里云主机折上折
  • 微信号
Current Site:Index > The string padding methods padStart() and padEnd()

The string padding methods padStart() and padEnd()

Author:Chuan Chen 阅读数:43082人阅读 分类: JavaScript

ECMAScript 8 (ES2017) introduced two practical string padding methods: padStart() and padEnd(). These methods allow developers to pad the beginning or end of a string with specified characters to achieve a target length. They are particularly useful in scenarios such as formatting output or aligning text.

The padStart() Method

The padStart() method pads the beginning of the original string with specified characters until the string reaches the target length. If the original string's length is already equal to or greater than the target length, the original string is returned unchanged.

Syntax

str.padStart(targetLength [, padString])
  • targetLength: The length of the resulting string after padding.
  • padString (optional): The string to pad with. Defaults to a space (" ").

Examples

  1. Basic Usage:

    const str = "123";
    console.log(str.padStart(5)); // "  123" (padded with spaces by default)
    console.log(str.padStart(5, "0")); // "00123"
    
  2. Padding String Exceeds Target Length: If the combined length of padString and the original string exceeds targetLength, padString is truncated.

    const str = "abc";
    console.log(str.padStart(5, "xyz")); // "xyabc" (only "xy" is used for padding)
    
  3. Original String Longer Than Target Length:

    const str = "hello";
    console.log(str.padStart(3, "0")); // "hello" (original string remains unchanged)
    
  4. Formatting Dates or Numbers:

    const month = "3";
    const day = "5";
    console.log(`${month.padStart(2, "0")}-${day.padStart(2, "0")}`); // "03-05"
    

The padEnd() Method

The padEnd() method is similar to padStart(), but it pads the end of the original string until it reaches the target length.

Syntax

str.padEnd(targetLength [, padString])
  • targetLength: The length of the resulting string after padding.
  • padString (optional): The string to pad with. Defaults to a space (" ").

Examples

  1. Basic Usage:

    const str = "123";
    console.log(str.padEnd(5)); // "123  " (padded with spaces by default)
    console.log(str.padEnd(5, "0")); // "12300"
    
  2. Padding String Exceeds Target Length:

    const str = "abc";
    console.log(str.padEnd(5, "xyz")); // "abcxy" (only "xy" is used for padding)
    
  3. Original String Longer Than Target Length:

    const str = "hello";
    console.log(str.padEnd(3, "0")); // "hello" (original string remains unchanged)
    
  4. Aligning Tabular Data:

    const data = [
      { name: "Alice", score: 95 },
      { name: "Bob", score: 88 },
    ];
    data.forEach(item => {
      console.log(`${item.name.padEnd(10)}: ${item.score}`);
    });
    // Output:
    // Alice     : 95
    // Bob       : 88
    

Practical Use Cases

Formatting Output

padStart() and padEnd() are commonly used for formatting output, such as aligning logs, tabular data, or numeric displays. For example, when printing a table to the console, they can be used to align columns:

const products = [
  { name: "Laptop", price: 999 },
  { name: "Phone", price: 699 },
  { name: "Tablet", price: 299 },
];
products.forEach(product => {
  console.log(`${product.name.padEnd(10)}: $${product.price.toString().padStart(4)}`);
});
// Output:
// Laptop    : $ 999
// Phone     : $ 699
// Tablet    : $ 299

Zero-Padding Numbers

When handling dates or times, it's often necessary to pad numbers with zeros to a fixed length:

function formatTime(hours, minutes, seconds) {
  return [
    hours.toString().padStart(2, "0"),
    minutes.toString().padStart(2, "0"),
    seconds.toString().padStart(2, "0"),
  ].join(":");
}
console.log(formatTime(5, 3, 9)); // "05:03:09"

Generating Fixed-Length Strings

In some scenarios, you may need to generate fixed-length strings (e.g., for IDs or codes):

function generateId(length) {
  const base = Math.random().toString(36).slice(2);
  return base.padEnd(length, "0").slice(0, length);
}
console.log(generateId(8)); // Example: "a1b2c3d0"

Notes

  1. Truncation of Padding String: If padString is not long enough to fill the remaining space, it will be repeated until the target length is reached. If padString is too long, it will be truncated.

  2. Handling Non-String Types: If the original string is not of string type, padStart() and padEnd() will first convert it to a string:

    console.log((123).toString().padStart(5, "0")); // "00123"
    
  3. Empty Strings or Invalid Parameters:

    • If padString is an empty string, the original string is returned unchanged.
    • If targetLength is negative, the original string is also returned unchanged.

Comparison with Other Methods

Before ES8, developers often had to manually implement string padding, such as using loops or Array.join():

function padStartManual(str, targetLength, padString = " ") {
  if (str.length >= targetLength) return str;
  const padLength = targetLength - str.length;
  let padding = "";
  for (let i = 0; i < padLength; i++) {
    padding += padString[i % padString.length];
  }
  return padding + str;
}
console.log(padStartManual("123", 5, "0")); // "00123"

In contrast, padStart() and padEnd() provide a more concise and efficient solution.

本站部分内容来自互联网,一切版权均归源网站或源作者所有。

如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn

Front End Chuan

Front End Chuan, Chen Chuan's Code Teahouse 🍵, specializing in exorcising all kinds of stubborn bugs 💻. Daily serving baldness-warning-level development insights 🛠️, with a bonus of one-liners that'll make you laugh for ten years 🐟. Occasionally drops pixel-perfect romance brewed in a coffee cup ☕.