--- title: String.prototype.padStart() slug: Web/JavaScript/Reference/Global_Objects/String/padStart tags: - ECMAScript 2017 - JavaScript - Method - Reference - String - String.padStart() translation_of: Web/JavaScript/Reference/Global_Objects/String/padStart ---
padStart()
方法用另一个字符串填充当前字符串(如果需要的话,会重复多次),以便产生的字符串达到给定的长度。从当前字符串的左侧开始填充。
str.padStart(targetLength [, padString])
targetLength
padString
{{optional_inline}}在原字符串开头填充指定的填充字符串直到目标长度所形成的新字符串。
'abc'.padStart(10); // " abc"
'abc'.padStart(10, "foo"); // "foofoofabc"
'abc'.padStart(6,"123465"); // "123abc"
'abc'.padStart(8, "0"); // "00000abc"
'abc'.padStart(1); // "abc"
如果原生环境不支持该方法,在其他代码之前先运行下面的代码,将创建 String.prototype.padStart()
方法。
// https://github.com/uxitten/polyfill/blob/master/string.polyfill.js
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padStart
if (!String.prototype.padStart) {
String.prototype.padStart = function padStart(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 padString.slice(0,targetLength) + String(this);
}
};
}
规范 | 状态 | 备注 |
---|---|---|
{{SpecName('ESDraft', '#sec-string.prototype.padstart', 'String.prototype.padStart')}} | {{Spec2('ESDraft')}} | 在 ECMAScript 2017 中首次被定义。 |
{{SpecName('ES8', '#sec-string.prototype.padstart', 'String.prototype.padStart')}} | {{Spec2('ES8')}} |
{{Compat("javascript.builtins.String.padStart")}}