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.
Key Features:
pad
function takes three arguments: the value to pad (input
), the desired length (length
), and the padding character (padding
).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; }
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);
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(':'));
Comparison to Alternative Approaches:
A simpler, but less robust approach would be:
while (input.length < length) { input = padding + input; } return input;
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!