JS 字符串:slice / substring / at / charAt 边界差异

面试高频:负索引、越界、start>end、返回值差异;推荐优先记 slice/at。

#resource / javascript #resource / ecmascript #type / concept #status / growing

[!info] related notes JavaScript / TypeScript 字符串方法

JS 字符串:slice / substring / at / charAt 边界差异

1) 一句话结论

  • 截取子串:优先用 slice(start, end?)(支持负索引,行为更直观)
  • 取单个字符:优先用 at(i)(支持负索引)或 str[i]

2) 取字符:charAt vs [] vs at

写法支持负索引越界返回备注
str.charAt(i)""老但稳定
str[i]undefined最常见
str.at(i)undefined现代,支持 -1

例子:

const s = "hello";

s.charAt(100); // ""
s[100];        // undefined
s.at(100);     // undefined

s.at(-1);      // "o"

3) 截取子串:slice vs substring

写法支持负索引start > end区间语义
slice(start, end?)返回 ""(不会交换)[start, end)
substring(start, end?)否(负数按 0 处理)会自动交换[start, end)

例子:

const s = "hello";

s.slice(1, 4);      // "ell"
s.substring(1, 4);  // "ell"

s.slice(4, 1);      // ""
s.substring(4, 1);  // "ell"

s.slice(-2);        // "lo"
s.substring(-2);    // "hello"  (-2 被当成 0)

4) 面试常问的易错点

  • length 是属性不是函数:s.length ✅,s.length()
  • substring 会交换参数,slice 不会
  • at(-1) 很好用,但旧环境可能不支持(面试可提“需要 polyfill/编译”)
创建于 2026/3/16 更新于 2026/5/27