如何使用JavaScript实现字符串的左右补齐功能并提高代码效率?

18 min read

可以使用以下代码实现padLeft和padRight的功能扩展:

String.prototype.padLeft = function (length, character = ' ') {
  return this.length >= length ? this : `${character.repeat(length - this.length)}${this}`;
};

String.prototype.padRight = function (length, character = ' ') {
  return this.length >= length ? this : `${this}${character.repeat(length - this.length)}`;
};

这样,你就可以在字符串对象上直接使用padLeft和padRight方法来补齐字符串的长度了。例如:

const name = 'John';
console.log(name.padLeft(10, '-'));  // ----John
console.log(name.padRight(10, '-')); // John-----

在上面的代码中,padLeft和padRight方法用于将名字'name'的长度补齐到10个字符,如果不够就使用'-'字符补齐。在padLeft方法中使用${character.repeat(length - this.length)}语句可以重复字符达到所需的长度,而在padRight方法中则是将字符添加在字符串的末尾。