The ECMAScript proposal “String padding” by Jordan Harband & Rick Waldron is part of ECMAScript 2017. This blog post explains it.
Use cases for padding strings include:
'file 001.txt'
'Test 001: ?'
'0x00FF'
String.prototype.padStart(maxLength, fillString=' ')
This method (possibly repeatedly) prefixes the receiver with fillString
, until its length is maxLength
:
> 'x'.padStart(5, 'ab')
'ababx'
If necessary, a fragment of fillString
is used so that the result’s length is exactly maxLength
:
> 'x'.padStart(4, 'ab')
'abax'
If the receiver is as long as, or longer than, maxLength
, it is returned unchanged:
> 'abcd'.padStart(2, '#')
'abcd'
If maxLength
and fillString.length
are the same, fillString
becomes a mask into which the receiver is inserted, at the end:
> 'abc'.padStart(10, '0123456789')
'0123456abc'
If you omit fillString
, a string with a single space in it is used (' '
):
> 'x'.padStart(3)
' x'
padStart()
The following implementation gives you a rough idea of how padStart()
works, but isn’t completely spec-compliant (for a few edge cases).
String.prototype.padStart =
function (maxLength, fillString=' ') {
let str = String(this);
if (str.length >= maxLength) {
return str;
}
fillString = String(fillString);
if (fillString.length === 0) {
fillString = ' ';
}
let fillLen = maxLength - str.length;
let timesToRepeat = Math.ceil(fillLen / fillString.length);
let truncatedStringFiller = fillString
.repeat(timesToRepeat)
.slice(0, fillLen);
return truncatedStringFiller + str;
};
String.prototype.padEnd(maxLength, fillString=' ')
padEnd()
works similarly to padStart()
, but instead of inserting the repeated fillString
at the start, it inserts it at the end:
> 'x'.padEnd(5, 'ab')
'xabab'
> 'x'.padEnd(4, 'ab')
'xaba'
> 'abcd'.padEnd(2, '#')
'abcd'
> 'abc'.padEnd(10, '0123456789')
'abc0123456'
> 'x'.padEnd(3)
'x '
Only the last line of an implementation of padEnd()
is different, compared to the implementation of padStart()
:
return str + truncatedStringFiller;
padLeft
and padRight
? For bidirectional or right-to-left languages, the terms left
and right
don’t work well. Therefore, the naming of padStart
and padEnd
follows the existing names startsWith
and endsWith
.
光绪是慈禧的什么人hcv7jop9ns3r.cn | 高密度脂蛋白胆固醇偏高什么意思zhongyiyatai.com | 外阴白斑是什么样子hcv8jop1ns4r.cn | 精液偏黄是什么原因hcv8jop4ns5r.cn | 给医生送锦旗写什么bfb118.com |
肝病初期有什么症状hcv8jop2ns9r.cn | 活动无耐力与什么有关bjhyzcsm.com | 单活胎是什么意思hcv8jop7ns3r.cn | 做梦梦见考试是什么意思gysmod.com | 氯低是什么原因hcv9jop6ns5r.cn |
青核桃皮的功效与作用是什么dayuxmw.com | 木犀读什么mmeoe.com | 夜里12点是什么时辰1949doufunao.com | 李嘉诚属什么生肖hcv9jop3ns8r.cn | 子宫内膜什么时候脱落hcv8jop2ns3r.cn |
禄位是什么意思hcv7jop6ns1r.cn | 大拇指疼痛什么原因引起的hcv9jop3ns8r.cn | 方脸适合什么刘海hcv8jop1ns5r.cn | 大林木是什么生肖hcv8jop1ns6r.cn | 荷兰豆为什么叫荷兰豆hcv8jop9ns8r.cn |