08.JavaScript 字符串方法完全指南
📋 速查对照表
🎯 一句话记忆口诀
.length 查长度,[] 取字符
.indexOf 找位置,.includes 查包含
.slice 截取好,.replace 替换掉
.toUpperCase 变大写,.toLowerCase 变小写
.trim 去空格,.split 分数组
.padStart 前补零,模板字符串最方便
字符串不可变,新串替换旧串
| 方法 |
功能描述 |
示例 |
| #基本信息 |
|
|
.length |
获取字符串长度 |
"Hi".length → 2 |
[] |
获取指定位置字符 |
"Hi"[1] → "i" |
| 查找与搜索 |
|
|
.indexOf() |
查找子串第一次出现位置 |
"abca".indexOf("a") → 0 |
.lastIndexOf() |
查找子串最后一次出现位置 |
"abca".lastIndexOf("a") → 3 |
.search() |
用正则表达式搜索 |
"Hello".search(/[A-Z]/) → 0 |
.includes() |
检查是否包含子串 |
"Hello".includes("el") → true |
.startsWith() |
检查是否以某串开头 |
"Hello".startsWith("He") → true |
.endsWith() |
检查是否以某串结尾 |
"Hello".endsWith("lo") → true |
.match() |
用正则表达式匹配 |
"Hello".match(/l/g) → ["l", "l"] |
.matchAll() |
匹配所有结果(ES2020) |
..."aa".matchAll(/a/g) |
| 截取与提取 |
|
|
.slice() |
截取指定位置子串 |
"Hello".slice(1,4) → "ell" |
.substring() |
截取子串(不支持负数) |
"Hello".substring(1,4) → "ell" |
.substr() |
按长度截取(已弃用) |
"Hello".substr(1,3) → "ell" |
.charAt() |
获取指定位置字符 |
"Hello".charAt(1) → "e" |
.charCodeAt() |
获取字符编码 |
"A".charCodeAt(0) → 65 |
.codePointAt() |
获取完整Unicode码点 |
"😊".codePointAt(0) → 128522 |
| 修改与转换 |
|
|
.replace() |
替换第一个匹配项 |
"aabb".replace("a","b") → "babb" |
.replaceAll() |
替换所有匹配项 |
"aabb".replaceAll("a","b") → "bbbb" |
.toUpperCase() |
转大写字母 |
"hello".toUpperCase() → "HELLO" |
.toLowerCase() |
转小写字母 |
"HELLO".toLowerCase() → "hello" |
.trim() |
去除前后空格 |
" hello ".trim() → "hello" |
.trimStart() |
去除开头空格 |
" hello ".trimStart() → "hello " |
.trimEnd() |
去除结尾空格 |
" hello ".trimEnd() → " hello" |
.padStart() |
在开头填充字符 |
"5".padStart(3,"0") → "005" |
.padEnd() |
在结尾填充字符 |
"5".padEnd(3,"0") → "500" |
.repeat() |
重复字符串 |
"ha".repeat(3) → "hahaha" |
.concat() |
连接多个字符串 |
"a".concat("b","c") → "abc" |
.normalize() |
Unicode正规化 |
"café".normalize() |
| 分割与组合 |
|
|
.split() |
分割字符串为数组 |
"a,b,c".split(",") → ["a","b","c"] |
+ 或 += |
连接字符串 |
"a" + "b" → "ab" |
| 模板字符串 |
连接字符串(ES6) |
`${"a"}${"b"}` → "ab" |
一、基本信息
1. .length – 获取字符串长度
let text = "Hello";
console.log(text.length); // 5(有5个字母)
2. [] – 通过下标获取字符
let text = "Hello";
console.log(text[0]); // "H"(第一个字符)
console.log(text[4]); // "o"(最后一个字符)
console.log(text[5]); // undefined(越界了)
二、查找与搜索
3. .indexOf() – 查找第一次出现的位置
let text = "Hello World";
console.log(text.indexOf("o")); // 4(第一个o的位置)
console.log(text.indexOf("World")); // 6(World开始的位置)
console.log(text.indexOf("abc")); // -1(没找到)
4. .lastIndexOf() – 查找最后一次出现的位置
let text = "Hello World Hello";
console.log(text.lastIndexOf("Hello")); // 12(第二个Hello的位置)
console.log(text.lastIndexOf("o")); // 15(最后一个o的位置)
5. .search() – 用正则表达式搜索
let text = "Hello World 123";
console.log(text.search(/World/)); // 6(找到World)
console.log(text.search(/d+/)); // 12(找到数字123)
console.log(text.search(/^Hello/)); // 0(以Hello开头)
6. .includes() – 检查是否包含
let text = "JavaScript很有趣";
console.log(text.includes("Java")); // true(包含Java)
console.log(text.includes("Python")); // false(不包含Python)
7. .startsWith() – 检查是否以某串开头
let filename = "document.pdf";
console.log(filename.startsWith("doc")); // true(以doc开头)
console.log(filename.startsWith("pdf")); // false(不以pdf开头)
8. .endsWith() – 检查是否以某串结尾
let filename = "document.pdf";
console.log(filename.endsWith(".pdf")); // true(以.pdf结尾)
console.log(filename.endsWith(".jpg")); // false(不以.jpg结尾)
9. .match() – 正则表达式匹配
let text = "我有3个苹果和5个香蕉";
console.log(text.match(/d+/g)); // ["3", "5"](所有数字)
console.log(text.match(/苹果/)); // ["苹果"](匹配苹果)
10. .matchAll() – 匹配所有结果(ES2020)
let text = "test1 test2 test3";
let matches = [...text.matchAll(/test(d)/g)];
console.log(matches[0][1]); // "1"(第一个匹配的数字)
console.log(matches[1][1]); // "2"(第二个匹配的数字)
三、截取与提取
11. .slice() – 截取子串(最推荐)
let text = "Hello World";
console.log(text.slice(0, 5)); // "Hello"(位置0到5)
console.log(text.slice(6)); // "World"(从位置6到最后)
console.log(text.slice(-5)); // "World"(最后5个字符)
console.log(text.slice(0, -6)); // "Hello"(从开头到倒数第6个)
12. .substring() – 截取子串(不支持负数)
let text = "Hello World";
console.log(text.substring(0, 5)); // "Hello"
console.log(text.substring(6)); // "World"
console.log(text.substring(6, 11)); // "World"
// 与slice的区别:自动交换参数
console.log(text.substring(5, 0)); // "Hello"(自动交换成0,5)
13. .substr() – 按长度截取(已弃用,了解即可)
let text = "Hello World";
console.log(text.substr(0, 5)); // "Hello"(从0开始,取5个)
console.log(text.substr(6)); // "World"(从6开始到最后)
console.log(text.substr(-5)); // "World"(最后5个字符)
14. .charAt() – 获取指定位置字符
let text = "Hello";
console.log(text.charAt(0)); // "H"
console.log(text.charAt(4)); // "o"
console.log(text.charAt(5)); // ""(空字符串,不报错)
15. .charCodeAt() – 获取字符编码
console.log("A".charCodeAt(0)); // 65(A的ASCII码)
console.log("中".charCodeAt(0)); // 20013(中的Unicode编码)
console.log("😊".charCodeAt(0)); // 55357(表情符号第一部分)
16. .codePointAt() – 获取完整Unicode码点
console.log("A".codePointAt(0)); // 65
console.log("中".codePointAt(0)); // 20013
console.log("😊".codePointAt(0)); // 128522(完整表情符号编码)
四、修改与转换
17. .replace() – 替换第一个匹配项
let text = "苹果好吃,苹果很甜";
console.log(text.replace("苹果", "香蕉"));
// "香蕉好吃,苹果很甜"(只替换第一个)
// 使用正则表达式替换所有
console.log(text.replace(/苹果/g, "香蕉"));
// "香蕉好吃,香蕉很甜"
18. .replaceAll() – 替换所有匹配项(ES2021)
let text = "苹果好吃,苹果很甜";
console.log(text.replaceAll("苹果", "香蕉"));
// "香蕉好吃,香蕉很甜"(替换所有)
// 也可以使用正则表达式
console.log(text.replaceAll(/苹果/g, "香蕉"));
// 同上
19. .toUpperCase() – 转大写
console.log("hello".toUpperCase()); // "HELLO"
console.log("Hello World".toUpperCase()); // "HELLO WORLD"
20. .toLowerCase() – 转小写
console.log("HELLO".toLowerCase()); // "hello"
console.log("Hello World".toLowerCase()); // "hello world"
21. .trim() – 去除前后空格
console.log(" hello ".trim()); // "hello"
console.log("n hello t".trim()); // "hello"(也去除换行符等)
22. .trimStart() – 去除开头空格
console.log(" hello ".trimStart()); // "hello "
23. .trimEnd() – 去除结尾空格
console.log(" hello ".trimEnd()); // " hello"
24. .padStart() – 在开头填充字符
console.log("5".padStart(3, "0")); // "005"
console.log("123".padStart(5, "0")); // "00123"
console.log("abc".padStart(10, "*")); // "*******abc"
25. .padEnd() – 在结尾填充字符
console.log("5".padEnd(3, "0")); // "500"
console.log("123".padEnd(5, "0")); // "12300"
console.log("abc".padEnd(10, "-")); // "abc-------"
26. .repeat() – 重复字符串
console.log("ha".repeat(3)); // "hahaha"
console.log("*".repeat(5)); // "*****"
console.log("abc".repeat(0)); // ""(空字符串)
27. .concat() – 连接字符串
console.log("Hello".concat(" ", "World")); // "Hello World"
console.log("a".concat("b", "c", "d")); // "abcd"
28. .normalize() – Unicode正规化(ES6)
let s1 = "café"; // 组合形式
let s2 = "cafeu0301"; // 分解形式
console.log(s1 === s2); // false
console.log(s1.normalize() === s2.normalize()); // true
五、分割与组合
29. .split() – 分割字符串为数组
let text = "苹果,香蕉,橙子";
console.log(text.split(",")); // ["苹果", "香蕉", "橙子"]
console.log("Hello".split("")); // ["H", "e", "l", "l", "o"]
console.log("a,b,c".split(",", 2)); // ["a", "b"](只分割2次)
// 用正则表达式分割
console.log("a b,c;d".split(/[s,;]+/)); // ["a", "b", "c", "d"]
30. + 和 += – 连接字符串
let firstName = "张";
let lastName = "三";
console.log(firstName + lastName); // "张三"
let greeting = "Hello";
greeting += " World";
console.log(greeting); // "Hello World"
31. 模板字符串(ES6推荐)
let name = "小明";
let age = 25;
console.log(`你好,${name}`); // "你好,小明"
console.log(`${name}今年${age}岁`); // "小明今年25岁"
console.log(`${5} + ${10} = ${5 + 10}`); // "5 + 10 = 15"
// 多行字符串(不需要n)
let letter = `亲爱的${name}:
你好!
祝你生日快乐!`;
六、重要特性与注意事项
1. 字符串不可变性
let str = "Hello";
str[0] = "J"; // ❌ 这不会改变字符串
console.log(str); // 还是"Hello"
// ✅ 正确做法:创建新字符串
let newStr = "J" + str.slice(1);
console.log(newStr); // "Jello"
2. 转义字符
console.log("他说:"你好""); // 他说:"你好"
console.log('It's me'); // It's me
console.log("第一行n第二行"); // 第一行(换行)第二行
console.log("路径:C:\Users"); // 路径:C:Users
3. 比较字符串
console.log("apple" === "apple"); // true
console.log("apple" === "Apple"); // false(大小写不同)
// 忽略大小写比较
console.log("apple".toLowerCase() === "Apple".toLowerCase()); // true
七、实用示例集锦
示例1:用户名格式化
function formatUsername(input) {
return input
.trim() // 去空格
.toLowerCase() // 转小写
.replace(/s+/g, "-"); // 空格转横线
}
console.log(formatUsername(" John Doe ")); // "john-doe"
示例2:手机号脱敏
function hidePhone(phone) {
return phone.slice(0, 3) + "****" + phone.slice(7);
}
console.log(hidePhone("13812345678")); // "138****5678"
示例3:密码强度检查
function checkPassword(password) {
let score = 0;
if (password.length >= 8) score++;
if (/[A-Z]/.test(password)) score++;
if (/[a-z]/.test(password)) score++;
if (/[0-9]/.test(password)) score++;
if (/[^A-Za-z0-9]/.test(password)) score++;
if (score <= 2) return "弱";
if (score <= 4) return "中";
return "强";
}
console.log(checkPassword("Abc123!@")); // "强"
示例4:生成随机验证码
function generateCode(length = 6) {
const chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
let code = "";
for (let i = 0; i < length; i++) {
code += chars.charAt(Math.floor(Math.random() * chars.length));
}
return code;
}
console.log(generateCode()); // 类似 "A3B9F2"
八、最佳实践总结
1. 常用方法优先级
// 1. 获取长度 → .length
// 2. 查找位置 → .indexOf() / .includes()
// 3. 截取子串 → .slice()
// 4. 替换内容 → .replace() / .replaceAll()
// 5. 大小写转换 → .toUpperCase() / .toLowerCase()
// 6. 去除空格 → .trim()
// 7. 分割字符串 → .split()
2. 性能建议
// ❌ 性能差:循环中使用 + 连接
let result = "";
for (let i = 0; i < 10000; i++) {
result += i; // 每次创建新字符串
}
// ✅ 性能好:使用数组join
let parts = [];
for (let i = 0; i < 10000; i++) {
parts.push(i);
}
let result2 = parts.join("");
3. 现代JavaScript特性
// 优先使用模板字符串
const name = "小明";
const age = 25;
// ❌ 老写法
const message1 = name + "今年" + age + "岁";
// ✅ 新写法(推荐)
const message2 = `${name}今年${age}岁`;