Home > Web Front-end > JS Tutorial > A Utility Function for Padding Strings and Numbers

A Utility Function for Padding Strings and Numbers

Joseph Gordon-Levitt
Release: 2025-02-25 11:29:11
Original
463 people have browsed it

This article introduces a JavaScript utility function, pad, for adding leading characters to strings or numbers, making them a specified length. This is particularly useful for formatting dates and times.

A Utility Function for Padding Strings and Numbers

Key Features:

  • The pad function takes three arguments: the value to pad (input), the desired length (length), and the padding character (padding).
  • It handles both string and numeric inputs, ensuring concatenation, not addition.
  • It's demonstrated formatting time (hours, minutes, seconds) into two-digit strings. Applications extend to dates, currency, and hex values.

Function Details:

The pad function's core logic is:

function pad(input, length, padding) {
  while ((input = input.toString()).length + (padding = padding.toString()).length < length) {
    padding += padding;
  }
  return padding.substr(0, length - input.length) + input;
}
Copy after login

The function cleverly pre-compiles the padding string to ensure correct padding even with multi-character padding strings. It then extracts the necessary portion to achieve the exact desired length.

Usage Examples:

Formatting the current hour to two digits:

var hours = pad(new Date().getHours(), 2, 0);
Copy after login

Creating a complete time string (HH:MM:SS):

var date = new Date(), time = [
  pad(date.getHours(), 2, 0),
  pad(date.getMinutes(), 2, 0),
  pad(date.getSeconds(), 2, 0)
];
alert(time.join(':'));
Copy after login

Comparison to Alternative Approaches:

A simpler, but less robust approach would be:

while (input.length < length) {
  input = padding + input;
}
return input;
Copy after login

This only works reliably with single-character padding strings. The pad function avoids this limitation.

Conclusion:

The pad function offers a concise and effective solution for a common formatting need. Its versatility extends beyond time formatting to various applications requiring padded strings or numbers.

The above is the detailed content of A Utility Function for Padding Strings and Numbers. For more information, please follow other related articles on the PHP Chinese website!

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