字符串的重复,追加补全也是常用的操作, ES 的新标准也为字符串添加了几个支持这样操作的函数,提供了操作的方便,之前一直没注意到这几个方法,这里做一个补充。
repeat
将源字符串重复多次后返回
string.repeat(count);
- count 指定字符串重复次数,重复次数不能小于0,如果是小数,会先取整数部分处理。
如果重复次数为小于等于-1的负数(-0.? 会先被取整数部分处理,所以不会报错)或者为 infinity
或者超过字符串的最大长度会抛出 [
RangeError](https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Errors/Negative_repetition_count)
异常。
示例:
`abc`.repeat(2); `abc`.repeat(2.1); `abc`.repeat(2.9); `abc`.repeat(0); `abc`.repeat(-1); `abc`.repeat(-0.9);
|
如果浏览器不支持此方法,可以使用如下的 Polyfill:
if (!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, padEnd
这两个方法提供了很方便的字符串长度补全,如果字符串的长度达不到指定的长度要求,两个函数分别会在字符串的开头或者结束位置补加上指定字符串,以使字符串达到指定长度。
string.padStart(targetLength [, padString])
staring.padEnd(targetLength [, padString])
示例:
'111'.padStart(10); '111'.padStart(10, 'abc'); '11111111'.padStart(10, 'abc'); '11111111'.padStart(3, 'abc'); '111'.padEnd(10); '111'.padEnd(10, 'abc'); '11111111'.padEnd(10, 'abc'); '11111111'.padEnd(3, 'abc');
|
如果浏览器不支持此方法,可以使用如下的 Polyfill:
if (!String.prototype.padStart) { String.prototype.padStart = function padStart(targetLength,padString) { targetLength = targetLength>>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); } return padString.slice(0,targetLength) + String(this); } }; }
|
padEnd 操作类似,只不过字符串追加的位置不同,不再补充。不过 polyfill 使用了 string.repeat
,所以可能还需要支持 string.repeat
函数。
参考