📌 总览速查表
| 类别 | 代表方法 |
|---|---|
| 查询 | charAt charCodeAt codePointAt indexOf includes startsWith endsWith |
| 截取 | slice substring split replace replaceAll |
| 大小写与填充 | toLowerCase toUpperCase trim padStart padEnd repeat |
| 正则 | match matchAll search |
| 工具 | String.raw 模板字符串 |
1️⃣ 读:查询 / 判断 / 定位
| 方法 | 概念 | 语法 | 场景示例 | 易错点 |
|---|---|---|---|---|
| charAt | 返回指定位置字符 | str.charAt(index) | 'abc'.charAt(1) → 'b' | index 越界返回空串 '' 而非 undefined |
| charCodeAt | 返回字符的 UTF-16 码点 | str.charCodeAt(i) | 'a'.charCodeAt(0) → 97 | 空串越界返回 NaN |
| codePointAt | 返回 Unicode 码点(支持四字) | str.codePointAt(i) | '
| 与 charCodeAt 结果差异大 |
| indexOf / lastIndexOf | 查找子串位置 | str.indexOf(sub[,from]) | 'hello'.indexOf('l') → 2 | 找不到返回 -1,不是 false |
| includes | ES6:子串是否存在 | str.includes(sub[,pos]) | 'abc'.includes('bc') → true | 区分大小写 |
| startsWith / endsWith | 前缀/后缀判断 | str.startsWith(sub) | 'file.txt'.endsWith('.txt') → true | 第二个参数为起始/结束索引 |
charAt
const str = 'JavaScript';
console.log(str.charAt(0)); // J 获取索引0字符
console.log(str.charAt(99)); // '' 越界返回空串
charCodeAt
const str = 'A';
console.log(str.charCodeAt(0)); // 65 返回UTF-16码点
// 越界返回 NaN
codePointAt
const str = '𠮷'; // 四字字符
console.log(str.codePointAt(0)); // 0x2000B Unicode码点
indexOf / lastIndexOf
const str = 'hello world';
console.log(str.indexOf('o')); // 4 首次出现
console.log(str.lastIndexOf('o')); // 7 最后出现
// 找不到返回 -1
includes
const str = 'hello';
console.log(str.includes('ell')); // true
console.log(str.includes('a')); // false
// 区分大小写
startsWith / endsWith
const file = 'report.pdf';
console.log(file.startsWith('rep')); // true
console.log(file.endsWith('.pdf')); // true
2️⃣ 截取 / 分割 / 替换
| 方法 | 概念 | 语法 | 场景示例 | 易错点 |
|---|---|---|---|---|
| slice | 非破坏截取 | str.slice(start,end) | 'abc'.slice(0,2) → 'ab' | 负索引从末尾算 |
| substring | 不接收负索引 | str.substring(start,end) | 同上 | start > end 自动交换 |
| substr | 已废弃 | str.substr(start,len) | 避免使用 | 未来会被移除 |
| split | 按分隔符拆成数组 | str.split(sep,limit) | 'abc'.split('')→['a','b','c'] | 空分隔符得到字符数组 |
| replace | 替换首个匹配 | str.replace(search,val) | 'a1b2'.replace(/\d/g,'#') → 'a#b#' | 只替换一次,需 /g 全局 |
| replaceAll | ES2021:全替换 | str.replaceAll('x','y') | 'xoxo'.replaceAll('x','X') → 'XoXo' | 正则必须带 g 标志 |
slice
const str = 'abcdef';
console.log(str.slice(1, 4)); // 'bcd' 包前不包后
console.log(str.slice(-3)); // 'def' 负索引从尾
substring
const str = 'abcdef';
console.log(str.substring(1, 4)); // 'bcd'
// 与 slice 区别:substring 不接受负索引
split
const csv = 'a,b,c';
const arr = csv.split(','); // ['a','b','c']
console.log(arr);
// 限制长度
console.log('a|b|c|d'.split('|', 2)); // ['a','b']
replace
const str = 'a1b2';
console.log(str.replace('1', '#')); // 'a#b2' 只替换第一次
console.log(str.replace(/\d/g, '#')); // 'a#b#' 全局正则
replaceAll
const str = 'xoxo';
console.log(str.replaceAll('x', 'X')); // 'XoXo'
// 正则必须带 g 标志
3️⃣ 大小写 & 空白处理
| 方法 | 概念 | 语法 | 场景示例 | 易错点 |
|---|---|---|---|---|
| toLowerCase / toUpperCase | 大小写转换 | str.toLowerCase() | ' ' | 对土耳其语等本地化大小写不友好 |
| trim / trimStart / trimEnd | 去空白 | str.trim() | ' hi '.trim() → 'hi' | 只去 Unicode 空白,不去 \u200B |
| trimLeft / trimRight | 别名 | 同 trimStart/End | 保持兼容,推荐用新名 | 暂无 |
toLowerCase / toUpperCase
const str = 'Java';
console.log(str.toLowerCase()); // 'java'
console.log(str.toUpperCase()); // 'JAVA'
trim / trimStart / trimEnd
const str = ' hello ';
console.log(str.trim()); // 'hello'
console.log(str.trimStart()); // 'hello '
console.log(str.trimEnd()); // ' hello'
4️⃣ 填充 / 重复 / 补位
| 方法 | 概念 | 语法 | 场景示例 | 易错点 |
|---|---|---|---|---|
| padStart / padEnd | 补位到指定长度 | str.padStart(len,pad) | ' ' | 若原串已 ≥ 长度,返回原串 |
| repeat | 重复 N 次 | str.repeat(count) | ' ' | count 不是整数会抛 RangeError |
padStart / padEnd
console.log('7'.padStart(3, '0')); // '007'
console.log('abc'.padEnd(6, '*')); // 'abc***'
repeat
console.log('ha'.repeat(3)); // 'hahaha'
// count 必须为 0~+∞ 整数,否则抛 RangeError
5️⃣ 模板与插值
| 概念 | 语法 | 场景示例 | 易错点 |
|---|---|---|---|
| 模板字符串 | `Hello ${name}` | 多行、插值、嵌入表达式 | 反引号内 ${} 之外的 $ 不会被解析 |
const name = 'Tom';
console.log(`Hello ${name}!`); // Hello Tom!
6️⃣ 正则相关高级工具
| 方法 | 概念 | 语法 | 场景示例 | 易错点 |
|---|---|---|---|---|
| match / matchAll | 提取匹配 | str.match(reg) | '
| matchAll 返回迭代器,需 g 标志 |
| search | 返回首次匹配索引 | str.search(reg) | 'abc'.search(/b/) → 1 | 找不到返回 -1 |
| split(正则版) | 按正则拆分 | str.split(/\s+/) | ' | 空串拆分需 /(?=.)/ |
match
const str = '2024-06-12';
console.log(str.match(/\d+/g)); // ['2024','06','12']
matchAll
const str = 'A1B2C3';
const matches = [...str.matchAll(/[A-Z]\d/g)];
console.log(matches); // [['A1'],['B2'],['C3']]
search
const str = 'hello';
console.log(str.search(/llo/)); // 2 返回索引
console.log(str.search(/xyz/)); // -1 找不到
7️⃣ 原始值包装 & 类型检测
| 方法 | 概念 | 语法 | 场景示例 | 易错点 |
|---|---|---|---|---|
| String.raw | 获取模板字符串原始文本 | String.raw | String.raw`C:\path\file`→C:\path\file` | 反斜杠不转义 |
| typeof / instanceof | 类型检测 |
| 区分 'abc' vs new String('abc') |
是对象 |
String.raw
// 场景:Windows 路径
const winPath = String.raw`C:\Users\docs\file.txt`;
console.log(winPath); // C:\Users\docs\file.txt
console.log(winPath === 'C:\\Users\\docs\\file.txt'); // true
// 对比普通模板字符串
const normal = `C:\Users\docs\file.txt`;
console.log(normal); // C:Usersdocsfile.txt ← \U \d 被当成转义
typeof / instanceof
// ------------ 原始值 ------------
const str1 = 'hello';
console.log(typeof str1); // "string"
console.log(str1 instanceof String); // false
// ------------ 包装对象 ------------
const str2 = new String('hello');
console.log(typeof str2); // "object" ← 注意!不是 "string"
console.log(str2 instanceof String); // true
console.log(str2.valueOf()); // "hello" ← 拿到原始值
// ------------ 判断是否为真正字符串 ------------
function isRealString(x) {
return typeof x === 'string' || x instanceof String;
}
console.log(isRealString(str1)); // true
console.log(isRealString(str2)); // true
8️⃣ 综合链式示例
const file = ' /User/docs/REPORT.txt ';
const clean = file
.trim() // 去首尾空格
.toLowerCase() // /user/docs/report.txt
.replace('.txt', '.md') // /user/docs/report.md
.split('/') // ['', 'user', 'docs', 'report.md']
.slice(-1)[0]; // 'report.md'
console.log(clean); // report.md
966

被折叠的 条评论
为什么被折叠?



