在线文档教程

string.padStart

string.padStart

padStart()方法用另一个字符串填充当前字符串(重复,如果需要的话),以便产生的字符串达到给定的长度。填充从当前字符串的开始(左侧)应用的。

语法

str.padStart(targetLength [, padString])

参数

targetLength当前字符串需要填充到的目标长度。如果这个数值小于当前字符串的长度,则返回当前字符串本身。

返回值

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

示例

'abc'.padStart(10 // "       abc" 'abc'.padStart(10, "foo" // "foofoofabc" 'abc'.padStart(6,"123465" // "123abc" 'abc'.padStart(8, "0" // "00000abc" 'abc'.padStart(1 // "abc"

Polyfill

Running the following code before any other code will create String.prototype.padStart() if it's not natively available.

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

规范

SpecificationStatusComment
ECMAScript Latest Draft (ECMA-262)The definition of 'String.prototype.padStart' in that specification.Living StandardInitial definition in ECMAScript 2017.
ECMAScript 2017 (ECMA-262)The definition of 'String.prototype.padStart' in that specification.Standard

浏览器兼容性

FeatureChromeEdgeFirefoxInternet ExplorerOperaSafari
Basic Support571548154410

FeatureAndroidChrome for AndroidEdge mobileFirefox for AndroidIE mobileOpera AndroidiOS Safari
Basic Support?57(Yes)48No?10