字符串常用方法

写出 16 个字符串常用方法:

补全/填充

  • padStart(maxLen, fillStr?) —— 头部补全到指定长度。
  • padEnd(maxLen, fillStr?) —— 尾部补全到指定长度。

查找

  • indexOf(str, fromIndex?) / lastIndexOf(str) —— 首次/末次出现的索引,找不到返回 -1。
  • includes(str, fromIndex?) —— 是否包含某子串。
  • search(regexp) —— 用正则查找,返回首个匹配索引或 -1。

提取与切片

  • charAt(index) —— 返回指定位置的字符(越界返回空字符串)。
  • slice(start?, end?) —— 切片(支持负数)。
  • substr(start, length?) —— 从 start 起取 length 个字符(已不推荐)。
  • substring(start, end?) —— 取 [start, end) 区间(不支持负数,会被当作 0)。

修改与拼接

  • replace(pattern, replacement) —— 替换第一个匹配;全局替换用正则加 g 标志。
  • split(separator?, limit?) —— 按分隔符拆成数组。
  • concat(str2, ...) —— 拼接字符串(一般用 + 或模板字符串代替)。
  • trim() / trimStart() / trimEnd() —— 去除两端/头部/尾部空白。
  • toUpperCase() / toLowerCase() —— 大小写转换。

补充(再补 4 个达到 16 个)

  • startsWith(str, position?) / endsWith(str, length?) —— 起始/结束判断。
  • repeat(count) —— 重复字符串 count 次。
  • charCodeAt(index) / codePointAt(index) —— 取字符的编码。
  • match(regexp) / matchAll(regexp) —— 正则匹配。

示例

'hello world'.padStart(15, '*');   // '****hello world'
'hello'.repeat(3);                  // 'hellohellohello'
'abcabc'.replace(/a/g, 'X');        // 'XbcXbc'
'1,2,3'.split(',');                 // ['1', '2', '3']

来源整理自:vue3js.cn 面试官系列