joken-前端工程师

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: :: :: 管理 ::

padStartpadEnd 是 JavaScript 中字符串方法,用于在字符串的开头或结尾添加填充字符,直到达到指定的长度。

padStart(targetLength, padString)

  • targetLength: 目标字符串长度。
  • padString: 用于填充的字符串。

用法:

const str = "hello";

// 在字符串开头添加空格,直到长度为 10
const paddedStart = str.padStart(10, " ");
console.log(paddedStart); // 输出 "     hello"

// 在字符串开头添加 "0",直到长度为 5
const paddedStart2 = str.padStart(5, "0");
console.log(paddedStart2); // 输出 "0hello"

padEnd(targetLength, padString)

  • targetLength: 目标字符串长度。
  • padString: 用于填充的字符串。

用法:

const str = "hello";

// 在字符串结尾添加空格,直到长度为 10
const paddedEnd = str.padEnd(10, " ");
console.log(paddedEnd); // 输出 "hello     "

// 在字符串结尾添加 "0",直到长度为 5
const paddedEnd2 = str.padEnd(5, "0");
console.log(paddedEnd2); // 输出 "hello0"

示例:

  • 格式化数字:
const num = 123;
const formattedNum = num.toString().padStart(5, "0");
console.log(formattedNum); // 输出 "00123"
  • 补全字符串:
const str = "hello";
const paddedStr = str.padEnd(10, "*");
console.log(paddedStr); // 输出 "hello*****"

注意:

  • 如果 targetLength 小于或等于字符串的当前长度,则不会进行填充。
  • 如果 padString 的长度大于 1,则会重复使用 padString 来填充。
  • 如果 padString 未指定,则默认使用空格进行填充。

padStartpadEnd 方法可以方便地对字符串进行填充,使它们符合特定的格式要求,例如格式化数字、补全字符串等。

测试

image

posted on 2024-08-15 21:42  joken1310  阅读(344)  评论(0)    收藏  举报