在 ECMAScript 2019 中,新增了两个字符串方法 padStart
和 padEnd
,用于在字符串的前面或后面填充指定的字符,使字符串达到指定的长度。这两个方法在前端开发中非常实用,本文将详细介绍它们的用法和示例。
padStart 方法
padStart
方法用于在字符串的前面填充指定的字符,使字符串达到指定的长度。其语法如下:
str.padStart(targetLength [, padString])
其中,targetLength
表示目标长度,即最终字符串需要达到的长度;padString
表示用于填充的字符,默认为 " "
(空格)。
例如,下面的代码将字符串 "hello"
前面填充了 3 个 "-"
,使其长度达到了 8:
const str = 'hello'; const paddedStr = str.padStart(8, '-'); console.log(paddedStr); // "---hello"
如果目标长度小于或等于原字符串的长度,则返回原字符串:
const str = 'hello'; const paddedStr = str.padStart(3, '-'); console.log(paddedStr); // "hello"
如果不指定填充字符,则使用默认的空格:
const str = 'hello'; const paddedStr = str.padStart(8); console.log(paddedStr); // " hello"
padEnd 方法
padEnd
方法用于在字符串的后面填充指定的字符,使字符串达到指定的长度。其语法如下:
str.padEnd(targetLength [, padString])
其中,targetLength
表示目标长度,即最终字符串需要达到的长度;padString
表示用于填充的字符,默认为 " "
(空格)。
例如,下面的代码将字符串 "hello"
后面填充了 3 个 "-"
,使其长度达到了 8:
const str = 'hello'; const paddedStr = str.padEnd(8, '-'); console.log(paddedStr); // "hello---"
如果目标长度小于或等于原字符串的长度,则返回原字符串:
const str = 'hello'; const paddedStr = str.padEnd(3, '-'); console.log(paddedStr); // "hello"
如果不指定填充字符,则使用默认的空格:
const str = 'hello'; const paddedStr = str.padEnd(8); console.log(paddedStr); // "hello "
总结
padStart
和 padEnd
方法非常实用,可以方便地将字符串填充到指定的长度。在前端开发中,经常需要对字符串进行格式化或对齐,这两个方法可以大大简化代码的编写。在使用时,需要注意目标长度和填充字符的选择,以便达到预期的效果。
示例代码:
-- -------------------- ---- ------- ----- --- - -------- ----- ---------- - --------------- ----- ----- ---------- - --------------- ----- ----- ---------- - ---------------- ----- ---------- - ------------- ----- ----- ---------- - ------------- ----- ----- ---------- - -------------- ------------------------ -- ---------- ------------------------ -- ------- ------------------------ -- - ------ ------------------------ -- ---------- ------------------------ -- ------- ------------------------ -- ------ -展开代码
来源:JavaScript中文网 ,转载请注明来源 https://www.javascriptcn.com/post/65616d4ed2f5e1655db7bd8b