String.prototype.padStart()

String 值的 padStart() 方法用另一个字符串填充此字符串(如果需要,可多次填充),直到结果字符串达到给定长度。填充是从该字符串的开头开始应用的。

¥The padStart() method of String values pads this string with another string (multiple times, if needed) until the resulting string reaches the given length. The padding is applied from the start of this string.

Try it

语法

¥Syntax

js
padStart(targetLength)
padStart(targetLength, padString)

参数

¥Parameters

targetLength

填充当前 str 后生成的字符串的长度。如果该值小于或等于 str.length,则按原样返回 str

padString Optional

用于填充当前 str 的字符串。如果 padString 太长而无法留在 targetLength 内,则会从末尾截断。默认值为 unicode "space" 字符 (U+0020)。

返回值

¥Return value

从一开始就应用指定的 targetLengthpadStringString

¥A String of the specified targetLength with padString applied from the start.

示例

¥Examples

基本示例

¥Basic examples

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

固定宽度字符串数字转换

¥Fixed width string number conversion

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 Language Specification
# sec-string.prototype.padstart

¥Specifications

浏览器兼容性

BCD tables only load in the browser

¥Browser compatibility

也可以看看