String.prototype.padStart()
Baseline Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since April 2017.
padStart()
方法用另一个字符串填充当前字符串(如果需要会重复填充),直到达到给定的长度。填充是从当前字符串的开头开始的。
尝试一下
const str1 = "5";
console.log(str1.padStart(2, "0"));
// Expected output: "05"
const fullNumber = "2034399002125581";
const last4Digits = fullNumber.slice(-4);
const maskedNumber = last4Digits.padStart(fullNumber.length, "*");
console.log(maskedNumber);
// Expected output: "************5581"
语法
js
padStart(targetLength)
padStart(targetLength, padString)
参数
targetLength
-
当前
str
填充后的长度。如果该值小于或等于str.length
,则会直接返回当前str
。 padString
可选-
用于填充当前
str
的字符串。如果padString
太长,无法适应targetLength
,则会从末尾被截断。默认值为 Unicode“空格”字符(U+0020)。
返回值
在开头填充 padString
直到达到给定的 targetLength
所形成的 String
。
示例
简单示例
js
"abc".padStart(10); // " abc"
"abc".padStart(10, "foo"); // "foofoofabc"
"abc".padStart(6, "123465"); // "123abc"
"abc".padStart(8, "0"); // "00000abc"
"abc".padStart(1); // "abc"
将数字转换为固定长度的字符串
js
// JavaScript version of: (unsigned)
// printf "%0*d" width num
function leftFillNum(num, targetLength) {
return num.toString().padStart(targetLength, "0");
}
const num = 123;
console.log(leftFillNum(num, 5)); // "00123"
规范
Specification |
---|
ECMAScript® 2025 Language Specification # sec-string.prototype.padstart |
浏览器兼容性
Report problems with this compatibility data on GitHubdesktop | mobile | server | ||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
padStart |
Legend
Tip: you can click/tap on a cell for more information.
- Full support
- Full support
The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request.