1 字符串基本特性
- 不可变性:所有方法都不修改原字符串,返回新字符串。
- 索引访问:str[index](只读)。
2 方法分类总结
2.1 字符串查找与索引
| 方法 | 作用说明 | 语法 | 返回值 | 示例 |
|---|
| charAt(index) | 获取指定索引字符 | str.charAt(index) | 字符或空字符串 | ’hello’.charAt(1) |
| indexOf(search) | 查找第一次出现的索引 | str.indexOf(search) | 索引或 -1 | ’hello’.indexOf(‘l’) |
| lastIndexOf(search) | 查找最后一次出现的索引 | str.lastIndexOf(search) | 索引或 -1 | ’hello’.lastIndexOf(‘l’) |
| includes(search) | 是否包含 | str.includes(search) | true/false | ’hello’.includes(‘ell’) |
| startsWith(search) | 是否以…开头 | str.startsWith(search) | true/false | ’hello’.startsWith(‘he’) |
| endsWith(search) | 是否以…结尾 | str.endsWith(search) | true/false | ’hello’.endsWith(‘lo’) |
2.2 字符串截取
| 方法 | 作用说明 | 语法 | 返回值 | 示例 |
|---|
| slice(start, end) | 截取 [start, end) 子串,支持负数 | str.slice(start, end) | 新字符串 | ’hello’.slice(1,4) → ‘ell’ |
| substring(start, end) | 截取 [start, end) 子串,负数视为0 | str.substring(start, end) | 新字符串 | ’hello’.substring(1,4) → ‘ell’ |
| substr(start, length) | 截取指定长度(已过时) | str.substr(start, length) | 新字符串 | ’hello’.substr(1,3) → ‘ell’ |
2.3 字符串修改(返回新的字符串)
| 方法 | 作用说明 | 语法 | 返回值 |
|---|
| trim() | 去除两端空白 | str.trim() | 新字符串 |
| padStart / padEnd | 填充至目标长度 | str.padStart(targetLen, padStr) | 新字符串 |
| repeat(count) | 重复字符串 | str.repeat(count) | 新字符串 |
| replace(search, replacement) | 替换第一个匹配 | str.replace(search, replacement) | 新字符串 |
| replaceAll(search, replacement) | 替换所有匹配(需/g) | str.replaceAll(search, replacement) | 新字符串 |
2.4 字符串转换
| 方法 | 作用说明 | 语法 | 返回值 |
|---|
| toLowerCase() | 转为小写 | str.toLowerCase() | 新字符串 |
| toUpperCase() | 转为大写 | str.toUpperCase() | 新字符串 |
| split(separator) | 拆分为数组 | str.split(separator) | 数组 |
2.5 正则相关方法
| 方法 | 作用说明 | 语法 | 返回值 |
|---|
| match(regex) | 查找正则匹配 | str.match(regex) | 数组或 null |
| search(regex) | 查找正则匹配索引 | str.search(regex) | 索引或 -1 |
3 注意事项
- 不可变性:必须接收返回值。
- slice vs substring:slice 支持负数索引,substring 负数视为 0 且会自动交换 start/end。
- replace vs replaceAll:replace 只替换第一个,全局需 /g;replaceAll 需正则带 /g。
- split() 技巧:split(”) 可将字符串拆分为单个字符数组。