Introduction to JS string completion methods padStart() and padEnd()

1. About string completion

String completion article thumbnail

In JS, string completion is a common operation, and the most commonly used is the complement before the time or date 0.

For example, for dates, we often use the 4-2-2 representation, such as:

2018-07-23

When we use the timestamp to get the month, there is no previous 0one, for example:

var month = new Date().getMonth() + 1; // the result is 7

Run result indication

At this point, it needs to be completed, the usual way is as follows:

if (month < 10) {
    month = '0' + month;
}

Even specifically define a fill '0'method, for example, this timestamp date transfer microcode custom in the zeromethod.

Completion method code schematic

However, with the emergence of JS string completion methods padStart()and padEnd(), similar scenarios are much easier to use!

2. About padStart

padStartYou can perform character completion at the beginning of the string.

The syntax is as follows:

str.padStart(targetLength [, padString])

among them:

  • targetLength (optional)
  • targetLengthRefers to the length of the target string.

    Then, according to my test, the targetLengthparameter will not report an error by default, and the original string is returned intact, but the code has no meaning. Therefore, there is basically no reason to use it.

    Also, targetLengththe type of the parameter can be a numeric type or a weak numeric type. In JavaScript 1 == '1', 1is a numeric value. '1'Although it is essentially a string, it can also be regarded as a weak numeric value. In the padStart()method, either a numeric type or a weak numeric type is acceptable. E.g:

    'zhangxinxu'.padStart('5');

    Therefore, when we actually use it, there is no need to targetLengthperform mandatory type conversion on the parameters.

    Finally, if the targetLengthset length is smaller than the string itself, the original string is returned intact, for example:

    'zhangxinxu'.padStart(5);     
    // The result is still'zhangxinxu'
  • padString (optional)
  • padStringRepresents the character string used to complete the length. However, although it is semantically a string, according to my test, any type of value is possible. Both the Chrome browser and the Firefox browser will try to convert this parameter into a string for completion. For example, the following examples:
    'zhangxinxu'.padStart(15, false);// The result is'falsezhangxinxu'
    'zhangxinxu'.padStart(15, null);// The result is'nullnzhangxinxu'
    'zhangxinxu'.padStart(15, []);// The result is'zhangxinxu', because [] converted to a string is an empty string
    'zhangxinxu'.padStart(15, {});// The result is'[objezhangxinxu', only the first 5 characters of'[object Object]' are displayed

    padStringThe default value of the parameter is ordinary space ' '(U+0020), which is the space that appears when you hit the Space key.

    It can be seen from the above cases that if the length of the completion string is insufficient, it will continue to complete it in a loop; if the length exceeds, it will be completed sequentially from the left, and the string that is not filled will be ignored.

The return value of this method is the completed string.

Going back to the date supplement '0'function at the beginning , with a padStart()method, our code can be simplified to the following line:

var month = String(new Date().getMonth() + 1).padStart(2, '0'); // The result is '07'

compatibility

IE14 is not supported by its existing browsers. Considering that it is still under Windows 7 now, the PC terminal can not be used directly for external projects; mobile terminals, UC browsers, and QQ browsers are not supported either. However, it is not unavailable, just add a Polyfill, which will be shown later.

3. About padEnd

padEndYou can perform character completion at the end of the string, and the grammatical parameters are padStartsimilar.

grammar:

str.padEnd(targetLength [, padString])

among them:

  • targetLength (optional)
  • targetLengthRefers to the length of the character string after completion.

    Then, according to my test, targetLengthif the parameter is not set, no error will be reported and the original string will be returned directly, but the code is meaningless. Therefore, in actual development, this parameter must be set.

    Similarly, targetLengththe type of the parameter can be a numeric type or a weak numeric type. For example, the following two usages are all possible:

    'zhangxinxu'.padEnd('15'); 
    'zhangxinxu'.padEnd(15);

    Therefore, when we actually write the code, there is no need to force the targetLengthparameters to be numeric values.

    Finally, if the targetLengthset length is smaller than the string itself, the original string is returned unchanged, for example:

    'zhangxinxu'.padEnd(5);     
    // The result is still'zhangxinxu'

    If it targetLengthis some messy numeric type, it also returns the original string. E.g:

    'zhangxinxu'.padEnd(false);     
    // The result is still'zhangxinxu'

    But does it make sense? It doesn't make sense, so don't use it like that.

  • padString (optional)
  • padStringRepresents the character string used to complete the length. Although semantically a string, in fact this parameter can be of various types. For example, the following examples:
    'zhangxinxu'.padEnd(15, false);// The result is'zhangxinxufalse'
    'zhangxinxu'.padEnd(15, null);// The result is'zhangxinxunulln'
    'zhangxinxu'.padEnd(15, []);// The result is'zhangxinxu', because [] converted to a string is an empty string
    'zhangxinxu'.padEnd(15, {});// The result is'zhangxinxu[obje', only the first 5 characters of'[object Object]' are displayed

    It can be seen from the above cases that if the length of the completion string is insufficient, it will continue to complete it from left to right; if the length exceeds the length of the character that can be completed, it will be completed as much as possible from the left, if it cannot be completed no way, can only be ignored, such as 'zhangxinxu'.padEnd(15, {})the equivalent to 'zhangxinxu'.padEnd(15, '[object Object]')a maximum of five characters can make, therefore, can only make '[object Object]'the first 5 characters, so the end result is: 'zhangxinxu[obje'.

    padStringIf the parameter is not set, the ordinary space ' '(U+0020) will be used instead, which is the space produced by the Space key.

    Take a case of completing a string in the back.
    When we process the timestamp in the JS front-end, the unit is msmilliseconds. However, the timestamp returned by the back-end students is not the same as milliseconds. It may only have 10 digits in sseconds. Therefore, when we process this timestamp on the front end, to be on the safe side, we must make a 13-bit completion first, and ensure that the unit is milliseconds. Usage hint:

    timestamp = +String(timestamp).padEnd(13, '0');

    compatibility

    This string API is a new method of ES6, IE14 does not support it because of its existing browsers, and some domestic mobile browsers do not support it. At present, the Polyfill code is required to be attached to external projects.

    Four, Polyfill code

    The following Polyfill code is taken from string.polyfill.js in the polyfill project. The dependency is repeat()also a new ES6 method. Therefore, the completion of the Polyfill code is as follows. I made a simple translation for the comment part, and the code part simplifies a little logic. At the same time, A bug has been fixed, the red highlighted part of the code below is the content of the fix:

    // https://github.com/uxitten/polyfill/blob/master/string.polyfill.js// repeat()方法的polyfillif (!String.prototype.repeat) {
        String.prototype.repeat = function (count) {
            'use strict';
            if (this == null) {
                throw new TypeError('can\'t convert ' + this + ' to object');
            }
            var str = '' + this;
            count = +count;
            if (count != count) {
                count = 0;
            }
            if (count < 0) {
                throw new RangeError('repeat count must be non-negative');
            }
            if (count == Infinity) {
                throw new RangeError('repeat count must be less than infinity');
            }
            count = Math.floor(count);
            if (str.length == 0 || count == 0) {
                return '';
            }
            if (str.length * count >= 1 << 28) {
                throw new RangeError('repeat count must not overflow maximum string size');
            }
            var rpt = '';
            for (; ;) {
                if ((count & 1) == 1) {
                    rpt += str;
                }
                count >>>= 1;
                if (count == 0) {
                    break;
                }
                str += str;
            }
            return rpt;
        }
    }// padStart()方法的polyfillif (!String.prototype.padStart) {
        String.prototype.padStart = function (targetLength, padString) {// Truncate numbers or convert non-numbers to 0 
            targetLength = targetLength>>0;  
            padString = String((typeof padString !=='undefined'? PadString: '') ); 
            if (this.length> targetLength || padString ==='') { 
                return String(this); 
            } 
            targetLength = targetLength-this.length; 
            if (targetLength> padString.length) {// add to the initial value Make sure the length is sufficient 
                padString += padString.repeat(targetLength / padString.length);  
            } 
            return padString.slice(0, targetLength) + String(this); 
        }; 
    }// polyfillif (!String.prototype.) of the padEnd() method. padEnd) {
        String.prototype.padEnd = function (targetLength, padString) {        // 转数值或者非数值转换成0
            targetLength = targetLength >> 0; 
            padString = String((typeof padString !== 'undefined' ? padString : ' '));
            if (this.length > targetLength || padString === '') {
                return String(this);
            }
            targetLength = targetLength - this.length;
            if (targetLength > padString.length) {            // 添加到初始值以确保长度足够
                padString += padString.repeat(targetLength / padString.length);
            }
            return String(this) + padString.slice(0, targetLength);
        };
    }

    The above polyfill code needs to be placed in front of the calling padStart()/ padEnd()method code, just paste it in the appropriate position, and then, no matter what version of the browser, even IE6, IE8, we can use padStart()or padEnd()method with confidence .

    Demo case under polyfill code

    You can click here: padStart and padEnd method polyfill test demo

    A bug in the original polyfill method was tested through this test demo. The following is a screenshot of the test results of the corrected polyfill code in IE9 browser:

    Screenshot of test results

    V. Conclusion

    Although the title is an introduction, the content of this article is actually very detailed. padStart()And the padEnd()two method parameters are very fault-tolerant, very characteristic of JS, I like it very much. However, it also brings another problem, that is, if our parameter value is not the parameter value we expect for various reasons, it is very likely to produce a very hidden bug, because there will be no errors, and the operation is still normal. . Therefore, strong fault tolerance can be considered both pros and cons.

    ES6 further extended strings many other methods, in addition to the herein mentioned repeat()methods, as well as normalize(), trimStart(), trimEnd()and other API method. After these, we will go into details one by one.


Guess you like

Origin blog.51cto.com/2096101/2663702