JS string completion methods padStart () and padEnd ()

Posted May 27, 20203 min read

This method is inadvertently seen, it feels quite practical, and I hereby share a wave. I think everybody will encounter that when the timestamp is converted into a time format, the time or date is less than 2 digits with a leading 0. With this thing said today, you can write a few lines of code again, you can use it when you encounter similar scenarios in the project.

ES2017 introduces the function of string length completion. If a certain string is not long enough, it will be completed at the head or tail.

padStart() padEnd() method fills the current string with another string(repeat if necessary) and returns the string that reaches the specified length after filling.

padStart() pads from the beginning(left) of the current string.
padEnd() starts padding from the end(right side) of the current string.

grammar:

str.padStart(targetLength \ [, padString ])
str.padEnd(targetLength \ [, padString ])

padStart() and padEnd() accept a total of two parameters. The first parameter targetLength is the target length to which the current string needs to be filled. The second parameter padString is the string used to fill. The default value is "".

return value:
Fill the specified filler character string at the beginning of the original character string to the new character string formed by the target length.

If targetLength is less than the length of the current string, string completion does not take effect, and the current string itself is returned.

'abc'.padStart(1,' d '); //"abc"
'abc'.padEnd(1,' d '); //"abc"

If targetLength is less than the sum of the length of the string used for padding and the length of the original string, the completed string exceeding the number of digits is truncated.

'abc'.padStart(6, "123456"); //"123abc"
'abc'.padEnd(6, "123456"); //"abc123"

If the second parameter padString is omitted, the length is filled with spaces.

'abc'.padStart(10); //"abc"
'abc'.padEnd(10); //"abc"

If the length of padString is too long, the extra string will be deleted.

'abc'.padStart(5, "foo"); //"foabc"
'abc'.padEnd(5, "foo"); //"abcfo"

application:

  • Completing the specified number of digits, such as formatting the time or date, the single digits are filled with 0
  • Tip string format String stitching

Examples:
When we use timestamp and convert to yyyy-mm-dd hh:mm:ss format.

function dataFormat(data) {
    const dt = new Date(data * 1000) //Note:If it is a 13-bit time stamp, do not use * 1000

    const y = dt.getFullYear()
    const m =(dt.getMonth() + 1 + '') .padStart(2, '0')
    const d =(dt.getDay() + '') .padStart(2, '0')

    const hh =(dt.getHours() + '') .padStart(2, '0')
    const mm =(dt.getMinutes() + '') .padStart(2, '0')
    const ss =(dt.getSeconds() + '') .padStart(2, '0')

    return `${y}-${m}-${d} ${hh}:${mm}:${ss}`
}

Because this method is new to ES6, some browsers do not support it, and there will be compatibility issues. View Polyfill created String.prototype.padStart()/String.prototype.padEnd() method

//https://github.com/uxitten/polyfill/blob/master/string.polyfill.js
//https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padEnd
if(! String.prototype.padEnd) {
    String.prototype.padEnd = function padEnd(targetLength, padString) {
        targetLength = targetLength >> 0; //floor if number or convert non-number to 0;
        padString = String((typeof padString! == 'undefined'? padString:''));
        if(this.length> targetLength) {
            return String(this);
        }
        else {
            targetLength = targetLength-this.length;
            if(targetLength> padString.length) {
                padString + = padString.repeat(targetLength/padString.length); //append to original to ensure we are longer than needed
            }
            return String(this) + padString.slice(0, targetLength);
        }
    };
}