js String padStart () operation autocomplete

Note string autocomplete function must be a string!

padStart (targetLength [, padString]) a method of filling the current string with another string (repeat if necessary), in order to produce the string reaches a given length. Filling a string from the beginning of the current application (left side).
targetLengt target length
padString supplementary string

var str1 = "1";
// 补充两位 场景:日期时间
var _str1 = sr1.padStart(2, '0') // '01'

// 补充多位 场景:单据号
var receiptNO = '1';
var _receiptNO = receiptNO.padStart(16, '0'); // '000000000000001';

Also you need to add Polyfill case of a supplementary browser does not support

If the native environment does not support this method, run the following code before any other code that will create String.prototype.padStart () method.

// https://github.com/uxitten/polyfill/blob/master/string.polyfill.js
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padStart
if (!String.prototype.padStart) {
    String.prototype.padStart = function padStart(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 padString.slice(0,targetLength) + String(this);
        }
    };
}
Published 58 original articles · won praise 20 · views 110 000 +

Guess you like

Origin blog.csdn.net/fly_wugui/article/details/103480336