--- title: String.prototype.padEnd() slug: Web/JavaScript/Reference/Global_Objects/String/padEnd tags: - JavaScript - Method - Reference - String translation_of: Web/JavaScript/Reference/Global_Objects/String/padEnd ---
padEnd()
方法会用一个字符串填充当前字符串(如果需要的话则重复填充),返回填充后达到指定长度的字符串。从当前字符串的末尾(右侧)开始填充。
str.padEnd(targetLength [, padString])
targetLength
padString
{{optional_inline}}在原字符串末尾填充指定的填充字符串直到目标长度所形成的新字符串。
'abc'.padEnd(10); // "abc " 'abc'.padEnd(10, "foo"); // "abcfoofoof" 'abc'.padEnd(6, "123456"); // "abc123" 'abc'.padEnd(1); // "abc"
如果原生环境不支持该方法,在其他代码之前先运行下面的代码,将创建 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 |
---|---|---|
{{SpecName('ESDraft', '#sec-string.prototype.padend', 'String.prototype.padEnd')}} | {{Spec2('ESDraft')}} | 在 ECMAScript 2017 中首次被定义。 |
{{SpecName('ES8', '#sec-string.prototype.padend', 'String.prototype.padEnd')}} | {{Spec2('ES8')}} |
{{Compat("javascript.builtins.String.padEnd")}}