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

The string padding methods padStart() and padEnd()

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

ECMAScript 7 String Padding Methods: padStart() and padEnd()

ECMAScript 7 introduced two new string methods: padStart() and padEnd(), which allow developers to easily pad a string with specified characters at the beginning or end until the string reaches the desired length. These methods are particularly useful for scenarios like string alignment and formatted output.

The padStart() Method

The padStart() method pads the beginning of a 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.

Syntax

str.padStart(targetLength [, padString])
  • targetLength: The target length of the string after padding.
  • padString (optional): The string used for padding. Defaults to a space.

Examples

const str = '42';

// Pad with spaces at the beginning until the string length is 5
console.log(str.padStart(5)); // "   42"

// Pad with '0' at the beginning until the string length is 5
console.log(str.padStart(5, '0')); // "00042"

// If the original string length exceeds the target length, return the original string
console.log(str.padStart(1, '0')); // "42"

// Use multiple characters as the padding string
console.log(str.padStart(6, 'abc')); // "abca42"

Practical Applications

padStart() is commonly used for number formatting, such as ensuring two-digit display for dates or times:

const hours = '3';
const minutes = '9';

console.log(`${hours.padStart(2, '0')}:${minutes.padStart(2, '0')}`); // "03:09"

The padEnd() Method

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

Syntax

str.padEnd(targetLength [, padString])
  • targetLength: The target length of the string after padding.
  • padString (optional): The string used for padding. Defaults to a space.

Examples

const str = 'Hello';

// Pad with spaces at the end until the string length is 10
console.log(str.padEnd(10)); // "Hello     "

// Pad with '.' at the end until the string length is 10
console.log(str.padEnd(10, '.')); // "Hello....."

// If the original string length exceeds the target length, return the original string
console.log(str.padEnd(3, '.')); // "Hello"

// Use multiple characters as the padding string
console.log(str.padEnd(11, ' World')); // "Hello World"

Practical Applications

padEnd() is often used for aligning text output, such as displaying tabular data in the console:

const products = [
  { name: 'Apple', price: 1.5 },
  { name: 'Banana', price: 0.5 },
  { name: 'Orange', price: 2.0 }
];

products.forEach(product => {
  console.log(`${product.name.padEnd(10)}: $${product.price.toFixed(2)}`);
});
// Apple     : $1.50
// Banana    : $0.50
// Orange    : $2.00

Truncation of Padding Strings

If the combined length of the padding string and the original string exceeds the target length, the padding string is truncated:

const str = '123';

// The padding string is truncated
console.log(str.padStart(5, 'abcdef')); // "ab123"
console.log(str.padEnd(5, 'abcdef')); // "123ab"

Comparison with Other Methods

Before ECMAScript 7, developers often had to manually implement string padding, such as using loops or the repeat() method:

// Manual implementation of padStart
function padStart(str, targetLength, padChar = ' ') {
  if (str.length >= targetLength) return str;
  return padChar.repeat(targetLength - str.length) + str;
}

console.log(padStart('42', 5, '0')); // "00042"

The introduction of padStart() and padEnd() simplifies this process, making the code more concise and readable.

Browser Compatibility

padStart() and padEnd() are widely supported in modern browsers, including Chrome, Firefox, Edge, and Safari. For older browsers that do not support these methods, a polyfill can be used:

if (!String.prototype.padStart) {
  String.prototype.padStart = function(targetLength, padString) {
    targetLength = targetLength >> 0;
    padString = String(padString || ' ');
    if (this.length >= targetLength) return String(this);
    const padLength = targetLength - this.length;
    return padString.repeat(Math.ceil(padLength / padString.length)).slice(0, padLength) + this;
  };
}

Performance Considerations

While padStart() and padEnd() are very convenient, performance may become an issue when processing large amounts of data. In such cases, consider using lower-level string operations or array concatenation for better performance.

// High-performance padStart implementation
function fastPadStart(str, targetLength, padChar = ' ') {
  if (str.length >= targetLength) return str;
  const padLength = targetLength - str.length;
  let result = '';
  for (let i = 0; i < padLength; i++) {
    result += padChar;
  }
  return result + str;
}

Integration with Other Language Features

padStart() and padEnd() can be combined with other ES6+ features, such as template literals and arrow functions:

const formatTime = (h, m, s) => 
  `${h.toString().padStart(2, '0')}:${m.toString().padStart(2, '0')}:${s.toString().padStart(2, '0')}`;

console.log(formatTime(9, 5, 2)); // "09:05:02"

Usage in Frameworks

In modern front-end frameworks like React and Vue, padStart() and padEnd() can be used to format displayed data:

function TimeDisplay({ hours, minutes }) {
  return (
    <div>
      {hours.toString().padStart(2, '0')}:{minutes.toString().padStart(2, '0')}
    </div>
  );
}

Special Use Cases

padStart() and padEnd() can also be used to create strings with specific formats, such as fixed-length IDs:

function generateId(num, length = 8) {
  return num.toString().padStart(length, '0');
}

console.log(generateId(42)); // "00000042"

Notes

  1. targetLength is converted to an integer. Passing non-numeric values may yield unexpected results:
console.log('42'.padStart('5')); // "   42" (normal)
console.log('42'.padStart('5.9')); // "   42" (5.9 is converted to 5)
console.log('42'.padStart(NaN)); // "42" (NaN is converted to 0)
  1. The padString parameter is optional and defaults to a space:
console.log('42'.padStart(5)); // "   42"
  1. If padString is an empty string, the original string is returned:
console.log('42'.padStart(5, '')); // "42"

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

如果侵犯了你的权益请来信告知我们删除。邮箱: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 ☕.