pFad - Phone/Frame/Anonymizer/Declutterfier! Saves Data!


--- a PPN by Garber Painting Akron. With Image Size Reduction included!

URL: https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/String/padStart

href="?u=http://developer.mozilla.org/static/client/inter-latin.9a3b1bc220d426ef.woff2" as="font" type="font/woff2" crossorigen="anonymous" fetchpriority="low" />

此页面由社区从英文翻译而来。了解更多并加入 MDN Web Docs 社区。

View in English Always switch to English

String.prototype.padStart()

基线 广泛可用

自 2017年4月 起,此特性已在主流浏览器中得到支持,可在大多数设备和浏览器版本中正常使用。

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"

规范

规范
ECMAScript® 2027 Language Specification
# sec-string.prototype.padstart

浏览器兼容性

参见

pFad - Phonifier reborn

Pfad - The Proxy pFad © 2024 Your Company Name. All rights reserved.





Check this box to remove all script contents from the fetched content.



Check this box to remove all images from the fetched content.


Check this box to remove all CSS styles from the fetched content.


Check this box to keep images inefficiently compressed and original size.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy