当前位置:首页 > 手册大全 > javascript手册 > String.prototype.padEnd()

padEnd()  方法会用一个字符串填充当前字符串(如果需要的话则重复填充),返回填充后达到指定长度的字符串。从当前字符串的末尾(右侧)开始填充。

语法

str.padEnd(targetLength [, padString])

参数

targetLength
当前字符串需要填充到的目标长度。如果这个数值小于当前字符串的长度,则返回当前字符串本身。
padString 可选
填充字符串。如果字符串太长,使填充后的字符串长度超过了目标长度,则只保留最左侧的部分,其他部分会被截断。此参数的缺省值为 " "(U+0020)。

返回值

在原字符串末尾填充指定的填充字符串直到目标长度所形成的新字符串。

示例

'abc'.padEnd(10);          // "abc       "
'abc'.padEnd(10, "foo");   // "abcfoofoof"
'abc'.padEnd(6, "123456"); // "abc123"
'abc'.padEnd(1);           // "abc"

腻子脚本(Polyfill)

如果原生环境不支持该方法,在其他代码之前先运行下面的代码,将创建 String.prototype.padEnd() 方法。

// 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);
        }
    };
}

规范

Specification Status Comment
ECMAScript Latest Draft (ECMA-262)
String.prototype.padEnd
Draft 在 ECMAScript 2017 中首次被定义。
ECMAScript 2017 (ECMA-262)
String.prototype.padEnd
Standard  

浏览器兼容性

Update compatibility data on GitHub
Desktop Mobile Server
Chrome Edge Firefox Internet Explorer Opera Safari Android webview Chrome for Android Edge Mobile Firefox for Android Opera for Android Safari on iOS Samsung Internet Node.js
Basic support Chrome Full support 57 Edge Full support 15 Firefox Full support 48 IE No support No Opera Full support 44 Safari Full support 10 WebView Android Full support 57 Chrome Android Full support 57 Edge Mobile Full support Yes Firefox Android Full support 48 Opera Android Full support 44 Safari iOS Full support 10 Samsung Internet Android Full support 7.0 nodejs Full support 8.0.0
Full support 8.0.0
Full support 7.0.0
Disabled
Disabled From version 7.0.0: this feature is behind the --harmony runtime flag.

Legend

Full support  
Full support
No support  
No support
User must explicitly enable this feature.
User must explicitly enable this feature.

另请参阅

公益性全栈资源网站,鸣谢默默付出的博主、工程师、架构师们。
网站内容来源技术大牛的辛勤结晶。
81For 技术网站 Copyright ©2019 备案号:津ICP备19001147号-2