js操作字符串的常用方法
1. 查找和截取
1.1 indexOf
-
作用:查找子字符串在字符串中首次出现的位置。
-
是否改变原字符串:不会改变原字符串。
-
返回值:如果找到子字符串,返回其起始索引(从 0 开始);如果未找到,返回
-1。
语法
string.indexOf(searchValue[, fromIndex])
-
searchValue:要查找的子字符串。 -
fromIndex(可选):从字符串的哪个索引位置开始查找,默认为 0。
1.1.1 基本用法
查找子字符串的位置:
const str = "Hello, world!";
const index = str.indexOf("world");console.log(index); // 输出: 7
console.log(str); // 输出: "Hello, world!" (原字符串未改变)
1.1.2 未找到子字符串
如果子字符串不存在,返回 -1:
const str = "Hello, world!";
const index = str.indexOf("foo");console.log(index); // 输出: -1
console.log(str); // 输出: "Hello, world!" (原字符串未改变)
1.1.3 指定起始位置
从指定索引位置开始查找:
const str = "Hello, world!";
const index = str.indexOf("o", 5);console.log(index); // 输出: 8 (从索引 5 开始查找,找到第二个 "o")
console.log(str); // 输出: "Hello, world!" (原字符串未改变)
1.1.4 查找空字符串
如果 searchValue 是空字符串,indexOf() 会返回 fromIndex 或 0:
const str = "Hello, world!";
const index1 = str.indexOf("");
const index2 = str.indexOf("", 5);console.log(index1); // 输出: 0
console.log(index2); // 输出: 5
console.log(str); // 输出: "Hello, world!" (原字符串未改变)
1.1.5 区分大小写
indexOf() 是区分大小写的:
const str = "Hello, world!";
const index = str.indexOf("World");console.log(index); // 输出: -1 (因为 "World" 和 "world" 大小写不匹配)
console.log(str); // 输出: "Hello, world!" (原字符串未改变)
1.1.6 总结
| 特性 | 说明 |
|---|---|
| 是否改变原字符串 | 不会改变原字符串。 |
| 返回值 | 如果找到子字符串,返回其起始索引;如果未找到,返回 -1。 |
| 区分大小写 | 是,区分大小写。 |
| 适用场景 | 查找子字符串在字符串中的位置。 |
1.1.7 注意事项
-
区分大小写:
indexOf()是区分大小写的。如果需要不区分大小写的查找,可以先将字符串转换为统一大小写:const str = "Hello, world!"; const index = str.toLowerCase().indexOf("world".toLowerCase());console.log(index); // 输出: 7 -
查找所有匹配项:
indexOf()只返回第一个匹配项的索引。如果需要查找所有匹配项,可以使用循环:const str = "Hello, world! world!"; const searchValue = "world"; let index = -1; const indices = [];while ((index = str.indexOf(searchValue, index + 1)) !== -1) {indices.push(index); }console.log(indices); // 输出: [7, 14] -
与
includes()的区别:-
indexOf()返回子字符串的索引。 -
includes()返回一个布尔值,表示是否包含子字符串。
-
1.2 lastIndexOf
-
作用:查找子字符串在字符串中最后一次出现的位置。
-
是否改变原字符串:不会改变原字符串。
-
返回值:如果找到子字符串,返回其起始索引(从 0 开始);如果未找到,返回
-1。
语法
string.lastIndexOf(searchValue[, fromIndex])
-
searchValue:要查找的子字符串。 -
fromIndex(可选):从字符串的哪个索引位置开始向前查找,默认为字符串的长度(即从末尾开始查找)。
1.2.1 基本用法
查找子字符串最后一次出现的位置:
const str = "Hello, world! world!";
const index = str.lastIndexOf("world");console.log(index); // 输出: 14 (第二个 "world" 的起始索引)
console.log(str); // 输出: "Hello, world! world!" (原字符串未改变)
1.2.2 未找到子字符串
如果子字符串不存在,返回 -1:
const str = "Hello, world!";
const index = str.lastIndexOf("foo");console.log(index); // 输出: -1
console.log(str); // 输出: "Hello, world!" (原字符串未改变)
1.2.3 指定起始位置
从指定索引位置开始向前查找:
const str = "Hello, world! world!";
const index = str.lastIndexOf("world", 10);console.log(index); // 输出: 7 (从索引 10 开始向前查找,找到第一个 "world")
console.log(str); // 输出: "Hello, world! world!" (原字符串未改变)
1.2.4 查找空字符串
如果 searchValue 是空字符串,lastIndexOf() 会返回 fromIndex 或字符串的长度:
const str = "Hello, world!";
const index1 = str.lastIndexOf("");
const index2 = str.lastIndexOf("", 5);console.log(index1); // 输出: 13 (字符串的长度)
console.log(index2); // 输出: 5
console.log(str); // 输出: "Hello, world!" (原字符串未改变)
1.2.5 区分大小写
lastIndexOf() 是区分大小写的:
const str = "Hello, World! world!";
const index = str.lastIndexOf("World");console.log(index); // 输出: 7 (因为 "World" 和 "world" 大小写不匹配,只找到 "World")
console.log(str); // 输出: "Hello, World! world!" (原字符串未改变)
1.2.6 总结
| 特性 | 说明 |
|---|---|
| 是否改变原字符串 | 不会改变原字符串。 |
| 返回值 | 如果找到子字符串,返回其起始索引;如果未找到,返回 -1。 |
| 查找方向 | 从字符串末尾开始向前查找。 |
| 区分大小写 | 是,区分大小写。 |
| 适用场景 | 查找子字符串在字符串中最后一次出现的位置。 |
1.2.7 注意事项
-
区分大小写:
lastIndexOf()是区分大小写的。如果需要不区分大小写的查找,可以先将字符串转换为统一大小写:const str = "Hello, World! world!"; const index = str.toLowerCase().lastIndexOf("world".toLowerCase());console.log(index); // 输出: 14 -
与
indexOf()的区别:-
indexOf()从字符串开头向后查找,返回第一次出现的位置。 -
lastIndexOf()从字符串末尾向前查找,返回最后一次出现的位置。
-
-
查找所有匹配项:
lastIndexOf()只返回最后一个匹配项的索引。如果需要查找所有匹配项,可以使用循环:const str = "Hello, world! world!"; const searchValue = "world"; let index = str.length; const indices = [];while ((index = str.lastIndexOf(searchValue, index - 1)) !== -1) {indices.push(index); }console.log(indices); // 输出: [14, 7] -
与
includes()的区别:-
lastIndexOf()返回子字符串的索引。 -
includes()返回一个布尔值,表示是否包含子字符串。
-
1.3 includes
-
作用:检查字符串中是否包含指定的子字符串。
-
是否改变原字符串:不会改变原字符串。
-
返回值:如果包含子字符串,返回
true;否则返回false。
语法
string.includes(searchValue[, fromIndex])
-
searchValue:要查找的子字符串。 -
fromIndex(可选):从字符串的哪个索引位置开始查找,默认为 0。
1.3.1 基本用法
检查字符串中是否包含子字符串:
const str = "Hello, world!";
const result = str.includes("world");console.log(result); // 输出: true
console.log(str); // 输出: "Hello, world!" (原字符串未改变)
1.3.2 未找到子字符串
如果子字符串不存在,返回 false:
const str = "Hello, world!";
const result = str.includes("foo");console.log(result); // 输出: false
console.log(str); // 输出: "Hello, world!" (原字符串未改变)
1.3.3 指定起始位置
从指定索引位置开始查找:
const str = "Hello, world!";
const result = str.includes("world", 8);console.log(result); // 输出: false (从索引 8 开始查找,未找到 "world")
console.log(str); // 输出: "Hello, world!" (原字符串未改变)
1.3.4 查找空字符串
如果 searchValue 是空字符串,includes() 会返回 true:
const str = "Hello, world!";
const result = str.includes("");console.log(result); // 输出: true
console.log(str); // 输出: "Hello, world!" (原字符串未改变)
1.3.5 区分大小写
includes() 是区分大小写的:
const str = "Hello, world!";
const result = str.includes("World");console.log(result); // 输出: false (因为 "World" 和 "world" 大小写不匹配)
console.log(str); // 输出: "Hello, world!" (原字符串未改变)
1.3.6 总结
| 特性 | 说明 |
|---|---|
| 是否改变原字符串 | 不会改变原字符串。 |
| 返回值 | 如果包含子字符串,返回 true;否则返回 false。 |
| 区分大小写 | 是,区分大小写。 |
| 适用场景 | 检查字符串中是否包含指定的子字符串。 |
1.3.7 注意事项
-
区分大小写:
includes()是区分大小写的。如果需要不区分大小写的查找,可以先将字符串转换为统一大小写:const str = "Hello, world!"; const result = str.toLowerCase().includes("WORLD".toLowerCase());console.log(result); // 输出: true -
与
startsWith()和endsWith()的区别:-
includes()检查子字符串是否存在于字符串的任何位置。 -
startsWith()检查字符串是否以指定的子字符串开头。 -
endsWith()检查字符串是否以指定的子字符串结尾。
-
1.4 startsWith
-
作用:检查字符串是否以指定的子字符串开头。
-
是否改变原字符串:不会改变原字符串。
-
返回值:如果字符串以指定的子字符串开头,返回
true;否则返回false。
语法
string.startsWith(searchValue[, fromIndex])
-
searchValue:要查找的子字符串。 -
fromIndex(可选):从字符串的哪个索引位置开始检查,默认为 0。
1.4.1 基本用法
检查字符串是否以指定的子字符串开头:
const str = "Hello, world!";
const result = str.startsWith("Hello");console.log(result); // 输出: true
console.log(str); // 输出: "Hello, world!" (原字符串未改变)
1.4.2 未找到匹配
如果字符串不是以指定的子字符串开头,返回 false:
const str = "Hello, world!";
const result = str.startsWith("world");console.log(result); // 输出: false
console.log(str); // 输出: "Hello, world!" (原字符串未改变)
1.4.3 指定起始位置
从指定索引位置开始检查:
const str = "Hello, world!";
const result = str.startsWith("world", 7);console.log(result); // 输出: true (从索引 7 开始检查,"world" 是开头的子字符串)
console.log(str); // 输出: "Hello, world!" (原字符串未改变)
1.4.4 查找空字符串
如果 searchValue 是空字符串,startsWith() 会返回 true:
const str = "Hello, world!";
const result = str.startsWith("");console.log(result); // 输出: true
console.log(str); // 输出: "Hello, world!" (原字符串未改变)
1.4.5 区分大小写
startsWith() 是区分大小写的:
const str = "Hello, world!";
const result = str.startsWith("hello");console.log(result); // 输出: false (因为 "hello" 和 "Hello" 大小写不匹配)
console.log(str); // 输出: "Hello, world!" (原字符串未改变)
1.4.6 总结
| 特性 | 说明 |
|---|---|
| 是否改变原字符串 | 不会改变原字符串。 |
| 返回值 | 如果字符串以指定的子字符串开头,返回 true;否则返回 false。 |
| 区分大小写 | 是,区分大小写。 |
| 适用场景 | 检查字符串是否以指定的子字符串开头。 |
1.4.7 注意事项
-
区分大小写:
startsWith()是区分大小写的。如果需要不区分大小写的检查,可以先将字符串转换为统一大小写:const str = "Hello, world!"; const result = str.toLowerCase().startsWith("hello".toLowerCase());console.log(result); // 输出: true -
与
endsWith()的区别:-
startsWith()检查字符串的开头。 -
endsWith()检查字符串的结尾。
-
1.5 endsWith
-
作用:检查字符串是否以指定的子字符串结尾。
-
是否改变原字符串:不会改变原字符串。
-
返回值:如果字符串以指定的子字符串结尾,返回
true;否则返回false。
语法
string.endsWith(searchValue[, length])
-
searchValue:要查找的子字符串。 -
length(可选):指定字符串的长度,即从字符串的开头到该长度的部分会被检查。默认为字符串的完整长度。
1.5.1 基本用法
检查字符串是否以指定的子字符串结尾:
const str = "Hello, world!";
const result = str.endsWith("world!");console.log(result); // 输出: true
console.log(str); // 输出: "Hello, world!" (原字符串未改变)
1.5.2 未找到匹配
如果字符串不是以指定的子字符串结尾,返回 false:
const str = "Hello, world!";
const result = str.endsWith("Hello");console.log(result); // 输出: false
console.log(str); // 输出: "Hello, world!" (原字符串未改变)
1.5.3 指定长度
检查字符串的前 n 个字符是否以指定的子字符串结尾:
const str = "Hello, world!";
const result = str.endsWith("Hello", 5);console.log(result); // 输出: true (检查前 5 个字符 "Hello" 是否以 "Hello" 结尾)
console.log(str); // 输出: "Hello, world!" (原字符串未改变)
1.5.4 查找空字符串
如果 searchValue 是空字符串,endsWith() 会返回 true:
const str = "Hello, world!";
const result = str.endsWith("");console.log(result); // 输出: true
console.log(str); // 输出: "Hello, world!" (原字符串未改变)
1.5.5 区分大小写
endsWith() 是区分大小写的:
const str = "Hello, world!";
const result = str.endsWith("World!");console.log(result); // 输出: false (因为 "World!" 和 "world!" 大小写不匹配)
console.log(str); // 输出: "Hello, world!" (原字符串未改变)
1.5.6 总结
| 特性 | 说明 |
|---|---|
| 是否改变原字符串 | 不会改变原字符串。 |
| 返回值 | 如果字符串以指定的子字符串结尾,返回 true;否则返回 false。 |
| 区分大小写 | 是,区分大小写。 |
| 适用场景 | 检查字符串是否以指定的子字符串结尾。 |
1.5.7 注意事项
-
区分大小写:
endsWith()是区分大小写的。如果需要不区分大小写的检查,可以先将字符串转换为统一大小写:const str = "Hello, world!"; const result = str.toLowerCase().endsWith("WORLD!".toLowerCase());console.log(result); // 输出: true
1.6 slice
-
作用:提取字符串的一部分。
-
是否改变原数据:不会改变原字符串。
-
返回值:返回一个新的字符串,包含提取的部分。
语法
string.slice(startIndex[, endIndex])
-
startIndex:提取的起始位置(包含该位置的元素)。 -
endIndex(可选):提取的结束位置(不包含该位置的元素)。如果省略,则提取到字符串或数组的末尾。
1.6.1 基本用法
提取字符串的一部分:
const str = "Hello, world!";
const result = str.slice(7, 12);console.log(result); // 输出: "world"
console.log(str); // 输出: "Hello, world!" (原字符串未改变)
1.6.2 省略结束位置(字符串)
如果省略 endIndex,则提取到字符串的末尾:
const str = "Hello, world!";
const result = str.slice(7);console.log(result); // 输出: "world!"
console.log(str); // 输出: "Hello, world!" (原字符串未改变)
1.6.3 使用负数索引(字符串)
负数索引表示从字符串末尾开始计算:
const str = "Hello, world!";
const result = str.slice(-6, -1);console.log(result); // 输出: "world"
console.log(str); // 输出: "Hello, world!" (原字符串未改变)
1.6.4 提取整个字符串
如果不传递任何参数,slice() 会返回整个字符串的副本:
const str = "Hello, world!";
const result = str.slice();console.log(result); // 输出: "Hello, world!"
console.log(str); // 输出: "Hello, world!" (原字符串未改变)
1.6.5 起始索引大于结束索引
如果 startIndex 大于 endIndex,slice() 会返回一个空字符串:
const str = "Hello, world!";
const result = str.slice(5, 2);console.log(result); // 输出: ""
console.log(str); // 输出: "Hello, world!" (原字符串未改变)
1.6.6 总结
| 特性 | 说明 |
|---|---|
| 是否改变原数据 | 不会改变原字符串或数组。 |
| 返回值 | 返回一个新的字符串或数组,包含提取的部分。 |
| 适用场景 | 提取字符串或数组的一部分。 |
1.6.7 注意事项
-
负数索引:
slice()支持负数索引,表示从末尾开始计算。 -
与
substring()的区别:-
slice()支持负数索引。 -
substring()不支持负数索引,且会将负数索引视为 0。
-
-
与
splice()的区别:-
slice()不会修改原字符串。 -
splice()会修改原字符串。
-
1.7 substring
-
作用:提取字符串的一部分。
-
是否改变原字符串:不会改变原字符串。
-
返回值:返回一个新的字符串,包含提取的部分。
语法
string.substring(startIndex[, endIndex])
-
startIndex:提取的起始位置(包含该位置的字符)。 -
endIndex(可选):提取的结束位置(不包含该位置的字符)。如果省略,则提取到字符串的末尾。
1.7.1 基本用法
提取字符串的一部分:
const str = "Hello, world!";
const result = str.substring(7, 12);console.log(result); // 输出: "world"
console.log(str); // 输出: "Hello, world!" (原字符串未改变)
1.7.2 省略结束位置
如果省略 endIndex,则提取到字符串的末尾:
const str = "Hello, world!";
const result = str.substring(7);console.log(result); // 输出: "world!"
console.log(str); // 输出: "Hello, world!" (原字符串未改变)
1.7.3 起始索引大于结束索引
如果 startIndex 大于 endIndex,substring() 会自动交换两个参数:
const str = "Hello, world!";
const result = str.substring(5, 2);console.log(result); // 输出: "llo" (相当于 str.substring(2, 5))
console.log(str); // 输出: "Hello, world!" (原字符串未改变)
1.7.4 使用负数索引
substring() 不支持负数索引,负数索引会被视为 0:
const str = "Hello, world!";
const result = str.substring(-5, 5);console.log(result); // 输出: "Hello" (负数索引 -5 被视为 0)
console.log(str); // 输出: "Hello, world!" (原字符串未改变)
1.7.5 提取整个字符串
如果不传递任何参数,substring() 会返回整个字符串的副本:
const str = "Hello, world!";
const result = str.substring();console.log(result); // 输出: "Hello, world!"
console.log(str); // 输出: "Hello, world!" (原字符串未改变)
1.7.6 总结
| 特性 | 说明 |
|---|---|
| 是否改变原字符串 | 不会改变原字符串。 |
| 返回值 | 返回一个新的字符串,包含提取的部分。 |
| 支持负数索引 | 不支持负数索引,负数索引会被视为 0。 |
| 适用场景 | 提取字符串的一部分。 |
1.7.7 注意事项
-
负数索引:
substring()不支持负数索引。如果传递负数索引,会被视为 0。 -
与
slice()的区别:-
slice()支持负数索引。 -
substring()不支持负数索引,且会将负数索引视为 0。 -
如果
startIndex大于endIndex,substring()会自动交换两个参数,而slice()会返回空字符串。
-
-
与
substr()的区别:-
substring()的第二个参数是结束索引(不包含)。 -
substr()的第二个参数是提取的长度。
-
1.8 substr
-
作用:从字符串中提取指定长度的子字符串。
-
是否改变原字符串:不会改变原字符串。
-
返回值:返回一个新的字符串,包含提取的部分。
语法
string.substr(startIndex[, length])
-
startIndex:提取的起始位置。-
如果为正数,表示从字符串开头计算的索引。
-
如果为负数,表示从字符串末尾计算的索引。
-
-
length(可选):提取的子字符串长度。如果省略,则提取到字符串的末尾。
1.8.1 基本用法
从字符串中提取指定长度的子字符串:
const str = "Hello, world!";
const result = str.substr(7, 5);console.log(result); // 输出: "world"
console.log(str); // 输出: "Hello, world!" (原字符串未改变)
1.8.2 省略长度
如果省略 length,则提取到字符串的末尾:
const str = "Hello, world!";
const result = str.substr(7);console.log(result); // 输出: "world!"
console.log(str); // 输出: "Hello, world!" (原字符串未改变)
1.8.3 使用负数索引
负数索引表示从字符串末尾开始计算:
const str = "Hello, world!";
const result = str.substr(-6, 5);console.log(result); // 输出: "world"
console.log(str); // 输出: "Hello, world!" (原字符串未改变)
1.8.4 起始索引超出范围
如果 startIndex 超出字符串的长度,substr() 会返回空字符串:
const str = "Hello, world!";
const result = str.substr(20, 5);console.log(result); // 输出: ""
console.log(str); // 输出: "Hello, world!" (原字符串未改变)
1.8.5 提取整个字符串
如果不传递任何参数,substr() 会返回整个字符串的副本:
const str = "Hello, world!";
const result = str.substr();console.log(result); // 输出: "Hello, world!"
console.log(str); // 输出: "Hello, world!" (原字符串未改变)
1.8.6 总结
| 特性 | 说明 |
|---|---|
| 是否改变原字符串 | 不会改变原字符串。 |
| 返回值 | 返回一个新的字符串,包含提取的部分。 |
| 支持负数索引 | 是,负数索引表示从字符串末尾开始计算。 |
| 适用场景 | 从字符串中提取指定长度的子字符串。 |
1.8.7 注意事项
-
负数索引:
substr()支持负数索引,表示从字符串末尾开始计算。 -
与
slice()的区别:-
substr()的第二个参数是提取的长度。 -
slice()的第二个参数是结束索引(不包含)。
-
-
与
substring()的区别:-
substr()支持负数索引。 -
substring()不支持负数索引,且会将负数索引视为 0。
-
-
遗留方法:
substr()已被标记为遗留方法,建议使用slice()或substring()替代。
2. 操作和修改
2.1 concat
-
作用:将多个字符串或数组合并为一个新的字符串或数组。
-
是否改变原数据:不会改变原字符串或数组。
-
返回值:返回一个新的字符串或数组,包含合并后的结果。
语法
string.concat(str1, str2, ..., strN)
-
str1, str2, ..., strN:要合并的字符串。
2.1.1 基本用法(字符串)
合并字符串:
const str1 = "Hello";
const str2 = " ";
const str3 = "world!";
const result = str1.concat(str2, str3);console.log(result); // 输出: "Hello world!"
console.log(str1); // 输出: "Hello" (原字符串未改变)
2.1.2 合并多个字符串
可以一次合并多个字符串:
const str = "Hello";
const result = str.concat(", ", "world", "!");console.log(result); // 输出: "Hello, world!"
console.log(str); // 输出: "Hello" (原字符串未改变)
2.1.3 合并空字符串
如果传递空字符串,concat() 会忽略它:
const str = "Hello";
const result = str.concat("", " world!", "");console.log(result); // 输出: "Hello world!"
console.log(str); // 输出: "Hello" (原字符串未改变)
2.1.4 合并非字符串类型
concat() 会将非字符串类型的参数转换为字符串:
const str = "Hello";
const result = str.concat(" ", 123, " ", true);console.log(result); // 输出: "Hello 123 true"
console.log(str); // 输出: "Hello" (原字符串未改变)
2.1.5 不传递参数
如果不传递任何参数,concat() 会返回原字符串的副本:
const str = "Hello";
const result = str.concat();console.log(result); // 输出: "Hello"
console.log(str); // 输出: "Hello" (原字符串未改变)
2.1.6 总结
| 特性 | 说明 |
|---|---|
| 是否改变原字符串 | 不会改变原字符串。 |
| 返回值 | 返回一个新的字符串,包含合并后的结果。 |
| 适用场景 | 合并多个字符串。 |
2.1.7 注意事项
-
与
+操作符的区别:-
concat()和+操作符的功能类似,都可以用于合并字符串。 -
+操作符的性能通常优于concat()。
-
-
非字符串类型:
-
concat()会将非字符串类型的参数转换为字符串。
-
-
性能:
-
如果需要合并大量字符串,建议使用
+操作符或模板字符串(`),因为它们的性能更好。
-
2.2 replace
-
作用:在字符串中查找并替换指定的子字符串或正则表达式匹配的内容。
-
是否改变原字符串:不会改变原字符串。
-
返回值:返回一个新的字符串,包含替换后的结果。
语法
string.replace(searchValue, replaceValue)
-
searchValue:要查找的内容,可以是字符串或正则表达式。 -
replaceValue:替换的内容,可以是字符串或函数。
2.2.1 基本用法(字符串替换)
替换字符串中的子字符串:
const str = "Hello, world!";
const result = str.replace("world", "JavaScript");console.log(result); // 输出: "Hello, JavaScript!"
console.log(str); // 输出: "Hello, world!" (原字符串未改变)
2.2.2 替换第一个匹配项
默认情况下,replace() 只会替换第一个匹配项:
const str = "apple, apple, apple";
const result = str.replace("apple", "orange");console.log(result); // 输出: "orange, apple, apple"
console.log(str); // 输出: "apple, apple, apple" (原字符串未改变)
2.2.3 使用正则表达式全局替换
使用正则表达式和 g 标志可以替换所有匹配项:
const str = "apple, apple, apple";
const result = str.replace(/apple/g, "orange");console.log(result); // 输出: "orange, orange, orange"
console.log(str); // 输出: "apple, apple, apple" (原字符串未改变)
2.2.4 使用函数作为替换值
replaceValue 可以是一个函数,函数的返回值将作为替换内容:
const str = "Hello, world!";
const result = str.replace("world", (match) => match.toUpperCase());console.log(result); // 输出: "Hello, WORLD!"
console.log(str); // 输出: "Hello, world!" (原字符串未改变)
2.2.5 使用捕获组
如果 searchValue 是正则表达式,并且包含捕获组,可以在 replaceValue 中使用 $1, $2 等引用捕获组:
const str = "2023-10-05";
const result = str.replace(/(\d{4})-(\d{2})-(\d{2})/, "$2/$3/$1");console.log(result); // 输出: "10/05/2023"
console.log(str); // 输出: "2023-10-05" (原字符串未改变)
2.2.6 替换特殊字符
如果 replaceValue 包含特殊字符(如 $),需要使用 $$ 进行转义:
const str = "The price is $10.";
const result = str.replace("$10", "$$5");console.log(result); // 输出: "The price is $5."
console.log(str); // 输出: "The price is $10." (原字符串未改变)
2.2.7 总结
| 特性 | 说明 |
|---|---|
| 是否改变原字符串 | 不会改变原字符串。 |
| 返回值 | 返回一个新的字符串,包含替换后的结果。 |
| 适用场景 | 查找并替换字符串中的子字符串或正则表达式匹配的内容。 |
2.2.8 注意事项
-
替换第一个匹配项:
-
如果
searchValue是字符串,replace()只会替换第一个匹配项。 -
如果需要替换所有匹配项,可以使用正则表达式并添加
g标志。
-
-
正则表达式:
-
如果
searchValue是正则表达式,可以使用捕获组和标志(如g、i等)。
-
-
函数作为替换值:
-
如果
replaceValue是函数,函数的参数依次为:-
match:匹配的子字符串。 -
p1, p2, ...:捕获组的内容(如果有)。 -
offset:匹配的子字符串在原字符串中的偏移量。 -
string:原字符串。
-
-
-
特殊字符:
-
如果
replaceValue包含$,需要使用$$进行转义。
-
2.3 replaceAll
-
作用:在字符串中查找并替换所有匹配的子字符串或正则表达式匹配的内容。
-
是否改变原字符串:不会改变原字符串。
-
返回值:返回一个新的字符串,包含替换后的结果。
语法
string.replaceAll(searchValue, replaceValue)
-
searchValue:要查找的内容,可以是字符串或正则表达式。-
如果是正则表达式,必须包含
g标志(全局匹配),否则会抛出错误。
-
-
replaceValue:替换的内容,可以是字符串或函数。
2.3.1 基本用法(字符串替换)
替换字符串中所有匹配的子字符串:
const str = "apple, apple, apple";
const result = str.replaceAll("apple", "orange");console.log(result); // 输出: "orange, orange, orange"
console.log(str); // 输出: "apple, apple, apple" (原字符串未改变)
2.3.2 使用正则表达式全局替换
如果 searchValue 是正则表达式,必须包含 g 标志:
const str = "apple, apple, apple";
const result = str.replaceAll(/apple/g, "orange");console.log(result); // 输出: "orange, orange, orange"
console.log(str); // 输出: "apple, apple, apple" (原字符串未改变)
2.3.3 使用函数作为替换值
replaceValue 可以是一个函数,函数的返回值将作为替换内容:
const str = "Hello, world! world!";
const result = str.replaceAll("world", (match) => match.toUpperCase());console.log(result); // 输出: "Hello, WORLD! WORLD!"
console.log(str); // 输出: "Hello, world! world!" (原字符串未改变)
2.3.4 替换特殊字符
如果 replaceValue 包含特殊字符(如 $),需要使用 $$ 进行转义:
const str = "The price is $10, $10, $10.";
const result = str.replaceAll("$10", "$$5");console.log(result); // 输出: "The price is $5, $5, $5."
console.log(str); // 输出: "The price is $10, $10, $10." (原字符串未改变)
2.3.5 替换空字符串
如果 searchValue 是空字符串,replaceAll() 会在每个字符之间插入 replaceValue:
const str = "abc";
const result = str.replaceAll("", "-");console.log(result); // 输出: "-a-b-c-"
console.log(str); // 输出: "abc" (原字符串未改变)
2.3.6 总结
| 特性 | 说明 |
|---|---|
| 是否改变原字符串 | 不会改变原字符串。 |
| 返回值 | 返回一个新的字符串,包含替换后的结果。 |
| 适用场景 | 查找并替换字符串中所有匹配的子字符串或正则表达式匹配的内容。 |
2.3.7 注意事项
-
全局替换:
-
replaceAll()会替换所有匹配项,而不像replace()默认只替换第一个匹配项。
-
-
正则表达式:
-
如果
searchValue是正则表达式,必须包含g标志,否则会抛出错误。
-
-
函数作为替换值:
-
如果
replaceValue是函数,函数的参数依次为:-
match:匹配的子字符串。 -
p1, p2, ...:捕获组的内容(如果有)。 -
offset:匹配的子字符串在原字符串中的偏移量。 -
string:原字符串。
-
-
-
特殊字符:
-
如果
replaceValue包含$,需要使用$$进行转义。
-
2.4 toLowerCase 的行为
-
作用:将字符串中的所有字符转换为小写。
-
是否改变原字符串:不会改变原字符串。
-
返回值:返回一个新的字符串,所有字符均为小写。
语法
string.toLowerCase()
2.4.1 基本用法
将字符串转换为小写:
const str = "Hello, World!";
const result = str.toLowerCase();console.log(result); // 输出: "hello, world!"
console.log(str); // 输出: "Hello, World!" (原字符串未改变)
2.4.2 处理非字母字符
toLowerCase() 只会影响字母字符,非字母字符(如数字、标点符号)不会改变:
const str = "123 Hello, World! 456";
const result = str.toLowerCase();console.log(result); // 输出: "123 hello, world! 456"
console.log(str); // 输出: "123 Hello, World! 456" (原字符串未改变)
2.4.3 处理 Unicode 字符
toLowerCase() 也支持 Unicode 字符:
const str = "ÄÖÜ";
const result = str.toLowerCase();console.log(result); // 输出: "äöü"
console.log(str); // 输出: "ÄÖÜ" (原字符串未改变)
2.4.4 处理空字符串
如果字符串为空,toLowerCase() 会返回空字符串:
const str = "";
const result = str.toLowerCase();console.log(result); // 输出: ""
console.log(str); // 输出: "" (原字符串未改变)
2.4.5 总结
| 特性 | 说明 |
|---|---|
| 是否改变原字符串 | 不会改变原字符串。 |
| 返回值 | 返回一个新的字符串,所有字符均为小写。 |
| 适用场景 | 将字符串中的所有字符转换为小写。 |
2.4.6 注意事项
-
非字母字符:
-
toLowerCase()只会影响字母字符,非字母字符(如数字、标点符号)不会改变。
-
-
Unicode 字符:
-
toLowerCase()支持 Unicode 字符,可以将大写字母(如Ä,Ö,Ü)转换为小写形式(如ä,ö,ü)。
-
-
性能:
-
toLowerCase()的性能通常很高,适合处理大量字符串。
-
2.5 toUpperCase
-
作用:将字符串中的所有字符转换为大写。
-
是否改变原字符串:不会改变原字符串。
-
返回值:返回一个新的字符串,所有字符均为大写。
语法
string.toUpperCase()
2.5.1 基本用法
将字符串转换为大写:
const str = "Hello, World!";
const result = str.toUpperCase();console.log(result); // 输出: "HELLO, WORLD!"
console.log(str); // 输出: "Hello, World!" (原字符串未改变)
2.5.2 处理非字母字符
toUpperCase() 只会影响字母字符,非字母字符(如数字、标点符号)不会改变:
const str = "123 Hello, World! 456";
const result = str.toUpperCase();console.log(result); // 输出: "123 HELLO, WORLD! 456"
console.log(str); // 输出: "123 Hello, World! 456" (原字符串未改变)
2.5.3 处理 Unicode 字符
toUpperCase() 也支持 Unicode 字符:
const str = "äöü";
const result = str.toUpperCase();console.log(result); // 输出: "ÄÖÜ"
console.log(str); // 输出: "äöü" (原字符串未改变)
2.5.4 处理空字符串
如果字符串为空,toUpperCase() 会返回空字符串:
const str = "";
const result = str.toUpperCase();console.log(result); // 输出: ""
console.log(str); // 输出: "" (原字符串未改变)
2.5.5 总结
| 特性 | 说明 |
|---|---|
| 是否改变原字符串 | 不会改变原字符串。 |
| 返回值 | 返回一个新的字符串,所有字符均为大写。 |
| 适用场景 | 将字符串中的所有字符转换为大写。 |
2.5.6 注意事项
-
非字母字符:
-
toUpperCase()只会影响字母字符,非字母字符(如数字、标点符号)不会改变。
-
-
Unicode 字符:
-
toUpperCase()支持 Unicode 字符,可以将小写字母(如ä,ö,ü)转换为大写形式(如Ä,Ö,Ü)。
-
-
性能:
-
toUpperCase()的性能通常很高,适合处理大量字符串。
-
2.6 trim 的行为
-
作用:去除字符串开头和结尾的空白字符。
-
是否改变原字符串:不会改变原字符串。
-
返回值:返回一个新的字符串,去除了开头和结尾的空白字符。
语法
string.trim()
2.6.1 基本用法
去除字符串开头和结尾的空白字符:
const str = " Hello, World! ";
const result = str.trim();console.log(result); // 输出: "Hello, World!"
console.log(str); // 输出: " Hello, World! " (原字符串未改变)
2.6.2 处理多种空白字符
trim() 会去除所有空白字符,包括空格、制表符(\t)、换行符(\n)等:
const str = "\t\n Hello, World! \t\n";
const result = str.trim();console.log(result); // 输出: "Hello, World!"
console.log(str); // 输出: "\t\n Hello, World! \t\n" (原字符串未改变)
2.6.3 处理空字符串
如果字符串为空或仅包含空白字符,trim() 会返回空字符串:
const str1 = "";
const str2 = " ";
const result1 = str1.trim();
const result2 = str2.trim();console.log(result1); // 输出: ""
console.log(result2); // 输出: ""
2.6.4 处理中间空白字符
trim() 不会去除字符串中间的空白字符:
const str = "Hello, World!";
const result = str.trim();console.log(result); // 输出: "Hello, World!"
console.log(str); // 输出: "Hello, World!" (原字符串未改变)
2.6.5 总结
| 特性 | 说明 |
|---|---|
| 是否改变原字符串 | 不会改变原字符串。 |
| 返回值 | 返回一个新的字符串,去除了开头和结尾的空白字符。 |
| 适用场景 | 去除字符串开头和结尾的空白字符。 |
2.6.7 注意事项
-
空白字符:
-
trim()会去除所有空白字符,包括空格、制表符(\t)、换行符(\n)等。
-
-
中间空白字符:
-
trim()不会去除字符串中间的空白字符。
-
-
兼容性:
-
trim()是 ES5 引入的方法,在现代浏览器和 Node.js 中广泛支持。
-
2.7 trimStart
-
作用:去除字符串开头的空白字符。
-
是否改变原字符串:不会改变原字符串。
-
返回值:返回一个新的字符串,去除了开头的空白字符。
语法
string.trimStart()
// 或
string.trimLeft()
2.7.1 基本用法
去除字符串开头的空白字符:
const str = " Hello, World! ";
const result = str.trimStart();console.log(result); // 输出: "Hello, World! "
console.log(str); // 输出: " Hello, World! " (原字符串未改变)
2.7.2 处理多种空白字符
trimStart() 会去除所有空白字符,包括空格、制表符(\t)、换行符(\n)等:
const str = "\t\n Hello, World! \t\n";
const result = str.trimStart();console.log(result); // 输出: "Hello, World! \t\n"
console.log(str); // 输出: "\t\n Hello, World! \t\n" (原字符串未改变)
2.7.3 处理空字符串
如果字符串为空或仅包含空白字符,trimStart() 会返回空字符串:
const str1 = "";
const str2 = " ";
const result1 = str1.trimStart();
const result2 = str2.trimStart();console.log(result1); // 输出: ""
console.log(result2); // 输出: ""
2.7.4 处理中间和结尾空白字符
trimStart() 不会去除字符串中间和结尾的空白字符:
const str = " Hello, World! ";
const result = str.trimStart();console.log(result); // 输出: "Hello, World! "
console.log(str); // 输出: " Hello, World! " (原字符串未改变)
2.7.5 总结
| 特性 | 说明 |
|---|---|
| 是否改变原字符串 | 不会改变原字符串。 |
| 返回值 | 返回一个新的字符串,去除了开头的空白字符。 |
| 适用场景 | 去除字符串开头的空白字符。 |
2.7.6 注意事项
-
空白字符:
-
trimStart()会去除所有空白字符,包括空格、制表符(\t)、换行符(\n)等。
-
-
中间和结尾空白字符:
-
trimStart()不会去除字符串中间和结尾的空白字符。
-
-
兼容性:
-
trimStart()是 ES2019 引入的方法,在现代浏览器和 Node.js 中广泛支持。
-
2.8 trimEnd 的行为
-
作用:去除字符串结尾的空白字符。
-
是否改变原字符串:不会改变原字符串。
-
返回值:返回一个新的字符串,去除了结尾的空白字符。
语法
string.trimEnd()
// 或
string.trimRight()
2.8.1 基本用法
去除字符串结尾的空白字符:
const str = " Hello, World! ";
const result = str.trimEnd();console.log(result); // 输出: " Hello, World!"
console.log(str); // 输出: " Hello, World! " (原字符串未改变)
2.8.2 处理多种空白字符
trimEnd() 会去除所有空白字符,包括空格、制表符(\t)、换行符(\n)等:
const str = "\t\n Hello, World! \t\n";
const result = str.trimEnd();console.log(result); // 输出: "\t\n Hello, World!"
console.log(str); // 输出: "\t\n Hello, World! \t\n" (原字符串未改变)
2.8.3 处理空字符串
如果字符串为空或仅包含空白字符,trimEnd() 会返回空字符串:
const str1 = "";
const str2 = " ";
const result1 = str1.trimEnd();
const result2 = str2.trimEnd();console.log(result1); // 输出: ""
console.log(result2); // 输出: ""
2.8.4 处理开头和中间空白字符
trimEnd() 不会去除字符串开头和中间的空白字符:
const str = " Hello, World! ";
const result = str.trimEnd();console.log(result); // 输出: " Hello, World!"
console.log(str); // 输出: " Hello, World! " (原字符串未改变)
2.8.5 总结
| 特性 | 说明 |
|---|---|
| 是否改变原字符串 | 不会改变原字符串。 |
| 返回值 | 返回一个新的字符串,去除了结尾的空白字符。 |
| 适用场景 | 去除字符串结尾的空白字符。 |
2.8.6 注意事项
-
空白字符:
-
trimEnd()会去除所有空白字符,包括空格、制表符(\t)、换行符(\n)等。
-
-
开头和中间空白字符:
-
trimEnd()不会去除字符串开头和中间的空白字符。
-
-
兼容性:
-
trimEnd()是 ES2019 引入的方法,在现代浏览器和 Node.js 中广泛支持。
-
3. 分割和转换
3.1 split
-
作用:将字符串按照指定的分隔符拆分为数组。
-
是否改变原字符串:不会改变原字符串。
-
返回值:返回一个数组,包含拆分后的子字符串。
语法
string.split([separator[, limit]])
-
separator(可选):分隔符,可以是字符串或正则表达式。如果省略,则返回包含原字符串的数组。 -
limit(可选):限制返回数组的长度。如果指定,则最多返回limit个元素。
3.1.1 基本用法
使用空格作为分隔符拆分字符串:
const str = "Hello world!";
const result = str.split(" ");console.log(result); // 输出: ["Hello", "world!"]
console.log(str); // 输出: "Hello world!" (原字符串未改变)
3.1.2 使用空字符串作为分隔符
将字符串拆分为单个字符的数组:
const str = "Hello";
const result = str.split("");console.log(result); // 输出: ["H", "e", "l", "l", "o"]
console.log(str); // 输出: "Hello" (原字符串未改变)
3.1.3 使用正则表达式作为分隔符
使用正则表达式拆分字符串:
const str = "Hello,world!JavaScript";
const result = str.split(/[,!]/);console.log(result); // 输出: ["Hello", "world", "JavaScript"]
console.log(str); // 输出: "Hello,world!JavaScript" (原字符串未改变)
3.1.4 限制返回数组的长度
使用 limit 参数限制返回数组的长度:
const str = "one,two,three,four";
const result = str.split(",", 2);console.log(result); // 输出: ["one", "two"]
console.log(str); // 输出: "one,two,three,four" (原字符串未改变)
3.1.5 不传递分隔符
如果不传递分隔符,则返回包含原字符串的数组:
const str = "Hello, world!";
const result = str.split();console.log(result); // 输出: ["Hello, world!"]
console.log(str); // 输出: "Hello, world!" (原字符串未改变)
3.1.6 处理空字符串
如果字符串为空,split() 会返回一个包含空字符串的数组:
const str = "";
const result = str.split(",");console.log(result); // 输出: [""]
console.log(str); // 输出: "" (原字符串未改变)
3.1.7 总结
| 特性 | 说明 |
|---|---|
| 是否改变原字符串 | 不会改变原字符串。 |
| 返回值 | 返回一个数组,包含拆分后的子字符串。 |
| 适用场景 | 将字符串按照指定的分隔符拆分为数组。 |
3.1.8 注意事项
-
分隔符:
-
如果
separator是空字符串,split()会将字符串拆分为单个字符的数组。 -
如果
separator未找到,split()会返回包含原字符串的数组。
-
-
正则表达式:
-
如果
separator是正则表达式,split()会根据正则表达式的匹配结果拆分字符串。
-
-
limit参数:-
如果指定
limit,则最多返回limit个元素。
-
3.2 charAt
-
作用:返回字符串中指定索引位置的字符。
-
是否改变原字符串:不会改变原字符串。
-
返回值:返回指定位置的字符。如果索引超出范围,则返回空字符串(
"")。
语法
string.charAt(index)
-
index:要获取字符的索引位置(从 0 开始)。如果为负数或大于等于字符串长度,则返回空字符串。
3.2.1 基本用法
获取字符串中指定位置的字符:
const str = "Hello, world!";
const result = str.charAt(1);console.log(result); // 输出: "e"
console.log(str); // 输出: "Hello, world!" (原字符串未改变)
3.2.2 索引超出范围
如果索引超出范围(负数或大于等于字符串长度),返回空字符串:
const str = "Hello, world!";
const result1 = str.charAt(-1);
const result2 = str.charAt(20);console.log(result1); // 输出: ""
console.log(result2); // 输出: ""
console.log(str); // 输出: "Hello, world!" (原字符串未改变)
3.2.3 获取第一个字符
获取字符串的第一个字符:
const str = "Hello, world!";
const result = str.charAt(0);console.log(result); // 输出: "H"
console.log(str); // 输出: "Hello, world!" (原字符串未改变)
3.2.4 获取最后一个字符
获取字符串的最后一个字符:
const str = "Hello, world!";
const result = str.charAt(str.length - 1);console.log(result); // 输出: "!"
console.log(str); // 输出: "Hello, world!" (原字符串未改变)
3.2.5 处理空字符串
如果字符串为空,charAt() 会返回空字符串:
const str = "";
const result = str.charAt(0);console.log(result); // 输出: ""
console.log(str); // 输出: "" (原字符串未改变)
3.2.6 总结
| 特性 | 说明 |
|---|---|
| 是否改变原字符串 | 不会改变原字符串。 |
| 返回值 | 返回指定位置的字符。如果索引超出范围,则返回空字符串。 |
| 适用场景 | 获取字符串中指定位置的字符。 |
3.2.7 注意事项
-
索引范围:
-
如果
index为负数或大于等于字符串长度,charAt()会返回空字符串。
-
-
与
[]访问符的区别:-
charAt()和[]都可以用于获取字符串中指定位置的字符。 -
如果索引超出范围,
charAt()返回空字符串,而[]返回undefined。
-
3.3 charCodeAt
-
作用:返回字符串中指定位置字符的 Unicode 编码。
-
是否改变原字符串:不会改变原字符串。
-
返回值:返回指定位置字符的 Unicode 编码(0 到 65535 之间的整数)。如果索引超出范围,则返回
NaN。
语法
string.charCodeAt(index)
-
index:要获取字符的索引位置(从 0 开始)。如果为负数或大于等于字符串长度,则返回NaN。
3.3.1 基本用法
获取字符串中指定位置字符的 Unicode 编码:
const str = "Hello, world!";
const result = str.charCodeAt(1);console.log(result); // 输出: 101 (字符 "e" 的 Unicode 编码)
console.log(str); // 输出: "Hello, world!" (原字符串未改变)
3.3.2 索引超出范围
如果索引超出范围(负数或大于等于字符串长度),返回 NaN:
const str = "Hello, world!";
const result1 = str.charCodeAt(-1);
const result2 = str.charCodeAt(20);console.log(result1); // 输出: NaN
console.log(result2); // 输出: NaN
console.log(str); // 输出: "Hello, world!" (原字符串未改变)
3.3.3 获取第一个字符的 Unicode 编码
获取字符串的第一个字符的 Unicode 编码:
const str = "Hello, world!";
const result = str.charCodeAt(0);console.log(result); // 输出: 72 (字符 "H" 的 Unicode 编码)
console.log(str); // 输出: "Hello, world!" (原字符串未改变)
3.3.4 获取最后一个字符的 Unicode 编码
获取字符串的最后一个字符的 Unicode 编码:
const str = "Hello, world!";
const result = str.charCodeAt(str.length - 1);console.log(result); // 输出: 33 (字符 "!" 的 Unicode 编码)
console.log(str); // 输出: "Hello, world!" (原字符串未改变)
3.3.5 处理空字符串
如果字符串为空,charCodeAt() 会返回 NaN:
const str = "";
const result = str.charCodeAt(0);console.log(result); // 输出: NaN
console.log(str); // 输出: "" (原字符串未改变)
3.3.6 总结
| 特性 | 说明 |
|---|---|
| 是否改变原字符串 | 不会改变原字符串。 |
| 返回值 | 返回指定位置字符的 Unicode 编码(0 到 65535 之间的整数)。如果索引超出范围,则返回 NaN。 |
| 适用场景 | 获取字符串中指定位置字符的 Unicode 编码。 |
3.3.7 注意事项
-
索引范围:
-
如果
index为负数或大于等于字符串长度,charCodeAt()会返回NaN。
-
-
Unicode 编码:
-
charCodeAt()返回的是 UTF-16 编码单元(0 到 65535 之间的整数)。 -
对于超出 BMP(基本多语言平面)的字符(如表情符号),
charCodeAt()只能返回代理对的第一个编码单元。如果需要完整的 Unicode 编码,可以使用codePointAt()。
-
3.4 fromCharCode
-
作用:将 Unicode 编码转换为对应的字符。
-
是否改变原字符串:不适用(静态方法,不依赖于实例)。
-
返回值:返回一个新的字符串,包含转换后的字符。
语法
String.fromCharCode(code1[, code2, ..., codeN])
-
code1, code2, ..., codeN:一个或多个 Unicode 编码(0 到 65535 之间的整数)。
3.4.1 基本用法
将 Unicode 编码转换为字符:
const result = String.fromCharCode(72, 101, 108, 108, 111);console.log(result); // 输出: "Hello"
3.4.2 处理单个编码
将单个 Unicode 编码转换为字符:
const result = String.fromCharCode(65);console.log(result); // 输出: "A"
3.4.3 处理多个编码
将多个 Unicode 编码转换为字符串:
const result = String.fromCharCode(128522, 128525);console.log(result); // 输出: "😊😍"
3.4.4 处理超出 BMP 的字符
fromCharCode() 只能处理 0 到 65535 之间的 Unicode 编码。对于超出 BMP(基本多语言平面)的字符(如表情符号),需要使用代理对:
const result = String.fromCharCode(55357, 56842); // 55357 和 56842 是 "😊" 的代理对console.log(result); // 输出: "😊"
3.4.5 处理无效编码
如果传递的编码无效(如负数或大于 65535),fromCharCode() 会返回不可预测的结果:
const result = String.fromCharCode(-1, 70000);console.log(result); // 输出: "�" (无效字符)
3.4.6 总结
| 特性 | 说明 |
|---|---|
| 是否改变原字符串 | 不适用(静态方法,不依赖于实例)。 |
| 返回值 | 返回一个新的字符串,包含转换后的字符。 |
| 适用场景 | 将 Unicode 编码转换为字符。 |
3.4.7 注意事项
-
编码范围:
-
fromCharCode()只能处理 0 到 65535 之间的 Unicode 编码。 -
对于超出 BMP 的字符(如表情符号),需要使用代理对。
-
-
与
codePointAt()的关系:-
codePointAt()用于获取字符的完整 Unicode 编码。 -
fromCharCode()用于将 Unicode 编码转换为字符。
-
-
与
String.fromCodePoint()的区别:-
fromCharCode()只能处理 0 到 65535 之间的编码。 -
String.fromCodePoint()可以处理完整的 Unicode 编码(包括超出 BMP 的字符)。
-
4. 其他方法
4.1 match
-
作用:在字符串中查找与正则表达式匹配的内容。
-
是否改变原字符串:不会改变原字符串。
-
返回值:
-
如果找到匹配项,返回一个数组,包含匹配结果。
-
如果未找到匹配项,返回
null。
-
语法
string.match(regexp)
-
regexp:一个正则表达式对象。如果传递的不是正则表达式,则会隐式转换为正则表达式。
4.1.1 基本用法
查找字符串中与正则表达式匹配的内容:
const str = "Hello, world!";
const result = str.match(/world/);console.log(result); // 输出: ["world", index: 7, input: "Hello, world!", groups: undefined]
console.log(str); // 输出: "Hello, world!" (原字符串未改变)
4.1.2 使用全局匹配
使用 g 标志进行全局匹配:
const str = "apple, apple, apple";
const result = str.match(/apple/g);console.log(result); // 输出: ["apple", "apple", "apple"]
console.log(str); // 输出: "apple, apple, apple" (原字符串未改变)
4.1.3 使用捕获组
如果正则表达式包含捕获组,match() 会返回捕获组的内容:
const str = "2023-10-05";
const result = str.match(/(\d{4})-(\d{2})-(\d{2})/);console.log(result); // 输出: ["2023-10-05", "2023", "10", "05", index: 0, input: "2023-10-05", groups: undefined]
console.log(str); // 输出: "2023-10-05" (原字符串未改变)
4.1.4 未找到匹配项
如果未找到匹配项,match() 返回 null:
const str = "Hello, world!";
const result = str.match(/foo/);console.log(result); // 输出: null
console.log(str); // 输出: "Hello, world!" (原字符串未改变)
4.1.5 处理空字符串
如果字符串为空,match() 会返回 null:
const str = "";
const result = str.match(/./);console.log(result); // 输出: null
console.log(str); // 输出: "" (原字符串未改变)
4.1.6 总结
| 特性 | 说明 |
|---|---|
| 是否改变原字符串 | 不会改变原字符串。 |
| 返回值 | 如果找到匹配项,返回一个数组;如果未找到匹配项,返回 null。 |
| 适用场景 | 在字符串中查找与正则表达式匹配的内容。 |
4.1.7 注意事项
-
全局匹配:
-
如果正则表达式包含
g标志,match()会返回所有匹配项的数组。 -
如果不包含
g标志,match()会返回第一个匹配项的详细信息(包括捕获组)。
-
-
捕获组:
-
如果正则表达式包含捕获组,
match()会返回捕获组的内容。
-
-
与
exec()的区别:-
match()是字符串的方法,返回匹配结果。 -
exec()是正则表达式的方法,返回匹配结果(与match()不包含g标志时的行为类似)。
-
4.1.8 示例对比
使用 match()
const str = "Hello, world!";
const result = str.match(/world/);console.log(result); // 输出: ["world", index: 7, input: "Hello, world!", groups: undefined]
使用 exec()
const regex = /world/;
const str = "Hello, world!";
const result = regex.exec(str);console.log(result); // 输出: ["world", index: 7, input: "Hello, world!", groups: undefined]
使用全局匹配
const str = "apple, apple, apple";
const result = str.match(/apple/g);console.log(result); // 输出: ["apple", "apple", "apple"]
4.2 search
-
作用:在字符串中查找与正则表达式匹配的内容,并返回第一个匹配项的索引。
-
是否改变原字符串:不会改变原字符串。
-
返回值:
-
如果找到匹配项,返回第一个匹配项的索引。
-
如果未找到匹配项,返回
-1。
-
语法
string.search(regexp)
-
regexp:一个正则表达式对象。如果传递的不是正则表达式,则会隐式转换为正则表达式。
4.2.1 基本用法
查找字符串中与正则表达式匹配的内容:
const str = "Hello, world!";
const result = str.search(/world/);console.log(result); // 输出: 7
console.log(str); // 输出: "Hello, world!" (原字符串未改变)
4.2.2 未找到匹配项
如果未找到匹配项,search() 返回 -1:
const str = "Hello, world!";
const result = str.search(/foo/);console.log(result); // 输出: -1
console.log(str); // 输出: "Hello, world!" (原字符串未改变)
4.2.3 使用字符串作为参数
如果传递的是字符串,search() 会将其隐式转换为正则表达式:
const str = "Hello, world!";
const result = str.search("world");console.log(result); // 输出: 7
console.log(str); // 输出: "Hello, world!" (原字符串未改变)
4.2.4 处理空字符串
如果字符串为空,search() 会返回 -1:
const str = "";
const result = str.search(/./);console.log(result); // 输出: -1
console.log(str); // 输出: "" (原字符串未改变)
4.2.5 使用捕获组
search() 会忽略正则表达式中的捕获组,只返回第一个匹配项的索引:
const str = "2023-10-05";
const result = str.search(/(\d{4})-(\d{2})-(\d{2})/);console.log(result); // 输出: 0
console.log(str); // 输出: "2023-10-05" (原字符串未改变)
4.2.6 总结
| 特性 | 说明 |
|---|---|
| 是否改变原字符串 | 不会改变原字符串。 |
| 返回值 | 如果找到匹配项,返回第一个匹配项的索引;如果未找到匹配项,返回 -1。 |
| 适用场景 | 在字符串中查找与正则表达式匹配的内容,并返回索引。 |
4.2.7 注意事项
-
全局匹配:
-
search()会忽略正则表达式中的g标志,只返回第一个匹配项的索引。
-
-
捕获组:
-
search()会忽略正则表达式中的捕获组,只返回第一个匹配项的索引。
-
-
与
indexOf()的区别:-
search()支持正则表达式。 -
indexOf()只支持字符串。
-
4.3 repeat
-
作用:将字符串重复指定次数。
-
是否改变原字符串:不会改变原字符串。
-
返回值:返回一个新的字符串,包含重复后的结果。
语法
string.repeat(count)
-
count:字符串重复的次数。必须是非负整数。
4.3.1 基本用法
将字符串重复指定次数:
const str = "Hello";
const result = str.repeat(3);console.log(result); // 输出: "HelloHelloHello"
console.log(str); // 输出: "Hello" (原字符串未改变)
4.3.2 重复 0 次
如果 count 为 0,repeat() 会返回空字符串:
const str = "Hello";
const result = str.repeat(0);console.log(result); // 输出: ""
console.log(str); // 输出: "Hello" (原字符串未改变)
4.3.3 重复小数
如果 count 是小数,repeat() 会将其向下取整:
const str = "Hello";
const result = str.repeat(2.5);console.log(result); // 输出: "HelloHello"
console.log(str); // 输出: "Hello" (原字符串未改变)
4.3.4 负数或无效参数
如果 count 为负数或无效参数,repeat() 会抛出错误:
const str = "Hello";try {const result = str.repeat(-1);console.log(result);
} catch (e) {console.log(e.message); // 输出: "Invalid count value"
}try {const result = str.repeat("abc");console.log(result);
} catch (e) {console.log(e.message); // 输出: "Invalid count value"
}
4.3.5 处理空字符串
如果字符串为空,repeat() 会返回空字符串:
const str = "";
const result = str.repeat(5);console.log(result); // 输出: ""
console.log(str); // 输出: "" (原字符串未改变)
4.3.6 总结
| 特性 | 说明 |
|---|---|
| 是否改变原字符串 | 不会改变原字符串。 |
| 返回值 | 返回一个新的字符串,包含重复后的结果。 |
| 适用场景 | 将字符串重复指定次数。 |
4.3.7 注意事项
-
参数范围:
-
count必须是非负整数。 -
如果
count是小数,会向下取整。 -
如果
count为负数或无效参数,会抛出错误。
-
-
性能:
-
如果
count很大,repeat()的性能可能会受到影响。
-
字符串方法
| 方法 | 作用 | 示例 |
|---|---|---|
indexOf | 返回子字符串的第一个索引 | 'hello'.indexOf('e') |
includes | 判断字符串是否包含子字符串 | 'hello'.includes('ell') |
slice | 提取字符串的一部分 | 'hello'.slice(1, 3) |
replace | 替换子字符串 | 'hello'.replace('he', 'she') |
toLowerCase | 将字符串转换为小写 | 'HELLO'.toLowerCase() |
toUpperCase | 将字符串转换为大写 | 'hello'.toUpperCase() |
trim | 去除字符串两端的空白字符 | ' hello '.trim() |
split | 将字符串分割为数组 | 'hello'.split('') |
charAt | 返回指定位置的字符 | 'hello'.charAt(1) |
match | 返回匹配正则表达式的子字符串 | 'hello'.match(/l/g) |
repeat | 将字符串重复指定次数 | 'hello'.repeat(2) |
通过掌握这些方法,可以更高效地处理字符串数据。
相关文章:
js操作字符串的常用方法
1. 查找和截取 1.1 indexOf 作用:查找子字符串在字符串中首次出现的位置。 是否改变原字符串:不会改变原字符串。 返回值:如果找到子字符串,返回其起始索引(从 0 开始);如果未…...
自动化学习-使用git进行版本管理
目录 一、为什么要学习git 二、git是什么 三、git如何使用 1、git的下载安装和配置 2、git常用的命令 3、gitee远程仓库的使用 (1)注册 (2)创建仓库 (3)配置公钥(建立电脑和git…...
GCC RISCV 后端 -- GCC Passes 注释
在前面文章提到,当GCC 前端完成对C源代码解析完成后,就会使用 处理过程(Passes)机制,通过一系列的处理过程,将 GENERIC IR 表示的C程序 转步转换成 目标机器的汇编语言。过程描述如下图所示: 此…...
Ollama存在安全风险的情况通报及解决方案
据清华大学网络空间测绘联合研究中心分析,开源跨平台大模型工具Ollama默认配置存在未授权访问与模型窃取等安全隐患。鉴于目前DeepSeek等大模型的研究部署和应用非常广泛,多数用户使用Ollama私有化部署且未修改默认配置,存在数据泄露、算力盗…...
IDEA Generate POJOs.groovy 踩坑小计 | 生成实体 |groovy报错
一、无法生成注释或生成的注释是null 问题可能的原因: 1.没有从表里提取注释信息,修改def calcFields(table)方法即可 def calcFields(table) {DasUtil.getColumns(table).reduce([]) { fields, col ->def spec Case.LOWER.apply(col.getDataType().…...
阿里云云监控资源告警常用模板
阿里云云监控资源告警常用模板 {"HostAvailabilityTemplate": [],"Description": "","SystemEventTemplates": [],"AlertTemplatesJson": {"kvstore_standard": [{"displayName": "Connection usa…...
Tailwind CSS 问题:npm error could not determine executable to run
问题与处理策略 问题描述 npx tailwindcss init -p在使用 Tailwind CSS 的前端项目中,执行上述指令,即初始化 Tailwind CSS 时,报如下错误 npm error could not determine executable to run# 报错npm 错误无法确定要运行的可执行文件问题…...
vue基本功
watchEffect和watch watchEffect默认 immdiate 是 true,而且自动收集依赖 watch需要手动写依赖,immdiate 默认是 false toRef和toRefs toRef: 复制 reactive 里的单个属性并转成 ref toRefs: 复制 reactive 里的所有属性并转成 ref vue3中使用vuex import { useStore } f…...
.NET10 - 预览版1新功能体验(一)
.NET 10 首个预览版已经在前两天发布,该版本在 .NET Runtime、SDK、libraries、C#、ASP.NET Core、Blazor 和 .NET MAUI 等多个方面都有重大改进和增强。其中C# 14 预览版也伴随着.NET 10预览版一起发布了,今天就和大家一起体验一下.NET 10 和 C# 14 。 …...
java下载多个网络文件并压缩成压缩包保存到本地
背景 开发票的时候远程会返回发票的url,现在客户端需要下载发票;因为一个订单可能不止一张发票,因此需要通过网络把远程的文件下载回来并压缩成压缩文件进行返回。 实现 本文的例子直接基于java.net包下面的类实现。(因为是基于…...
23种设计模式之单例模式(Singleton Pattern)【设计模式】
文章目录 一、简介二、关键点三、实现单例模式的步骤四、C#示例4.1 简单的单例模式4.2 线程安全的单例模式(双重检查锁定)4.3 静态初始化单例模式 五、单例模式优缺点5.1 优点5.2 缺点 六、适用场景七、示例的现实应用 一、简介 单例模式(Si…...
[项目]基于FreeRTOS的STM32四轴飞行器: 四.LED控制
基于FreeRTOS的STM32四轴飞行器: 四.LED控制 一.配置Com层二.编写驱动 一.配置Com层 先在Com_Config.h中定义灯位置的枚举类型: 之后定义Led的结构体: 定义飞行器状态: 在Com_Config.c中初始化四个灯: 在Com_Config.h外部声明…...
使用 dynamic-datasource-spring-boot-starter 实现多数据源动态切换
目录 在实际开发中,我们经常会遇到需要在一个项目中连接多个数据源的场景。例如,一个应用可能需要同时访问多个数据库,或者根据业务需求动态切换数据源。dynamic-datasource-spring-boot-starter 是一个基于 Spring Boot 的轻量级多数据源动态…...
springboot中注解有什么用
注解(Annotation)是 Java 的一个重要特性,我用几个具体例子来解释: 1、标记功能 Service // 告诉Spring这是一个服务类 public class UserService { }Data // 告诉Lombok自动生成getter/setter public class User {private…...
Spring Boot 缓存最佳实践:从基础到生产的完整指南
Spring Boot 缓存最佳实践:从基础到生产的完整指南 引言 在现代分布式系统中,缓存是提升系统性能的银弹。Spring Boot 通过 spring-boot-starter-cache 模块提供了开箱即用的缓存抽象,但如何根据业务需求实现灵活、可靠的缓存方案…...
Linux网络相关内容与端口
网络相关命令 ping命令测试连接状态 wget命令:非交互式文件下载器,可以在命令行内下载网络文件 使用ctrlc可以中止下载 curl命令:可以发送http网络请求,用于文件下载、获取信息等 其实和浏览器打开网站一样,cu…...
Python Flask框架学习汇编
1、入门级: 《Python Flask Web 框架入门》 这篇博文条理清晰,由简入繁,案例丰富,分十五节详细讲解了Flask框架,强烈推荐! 《python的简单web框架flask【附例子】》 讲解的特别清楚,每一步都…...
GitHub CI流水线
GitHub CI流水线 build.yml 路径:.github/workflows/build.yml name: Docker Image CIon:workflow_dispatch:jobs:build:runs-on: ubuntu-lateststeps:- uses: actions/checkoutv4- name: Set up JDK 8uses: actions/setup-javav4with:java-version: 8distributi…...
机器视觉运动控制一体机在天地盖同步跟随贴合解决方案
市场应用背景 纸盒天地盖是一种包装形式,广泛应用于消费电子、食品礼盒、奢侈品及化妆品等领域。其采用高强度纸板,经过预组装处理,结构坚固稳定,能有效保护产品并提升品牌形象。随着包装行业快速发展,市场对天地盖的…...
贪心算法一
> 作者:დ旧言~ > 座右铭:松树千年终是朽,槿花一日自为荣。 > 目标:了解什么是贪心算法,并且掌握贪心算法。 > 毒鸡汤:有些事情,总是不明白,所以我不会坚持。早安! >…...
内存分配函数malloc kmalloc vmalloc
内存分配函数malloc kmalloc vmalloc malloc实现步骤: 1)请求大小调整:首先,malloc 需要调整用户请求的大小,以适应内部数据结构(例如,可能需要存储额外的元数据)。通常,这包括对齐调整,确保分配的内存地址满足特定硬件要求(如对齐到8字节或16字节边界)。 2)空闲…...
Appium+python自动化(十六)- ADB命令
简介 Android 调试桥(adb)是多种用途的工具,该工具可以帮助你你管理设备或模拟器 的状态。 adb ( Android Debug Bridge)是一个通用命令行工具,其允许您与模拟器实例或连接的 Android 设备进行通信。它可为各种设备操作提供便利,如安装和调试…...
Vue3 + Element Plus + TypeScript中el-transfer穿梭框组件使用详解及示例
使用详解 Element Plus 的 el-transfer 组件是一个强大的穿梭框组件,常用于在两个集合之间进行数据转移,如权限分配、数据选择等场景。下面我将详细介绍其用法并提供一个完整示例。 核心特性与用法 基本属性 v-model:绑定右侧列表的值&…...
循环冗余码校验CRC码 算法步骤+详细实例计算
通信过程:(白话解释) 我们将原始待发送的消息称为 M M M,依据发送接收消息双方约定的生成多项式 G ( x ) G(x) G(x)(意思就是 G ( x ) G(x) G(x) 是已知的)࿰…...
《用户共鸣指数(E)驱动品牌大模型种草:如何抢占大模型搜索结果情感高地》
在注意力分散、内容高度同质化的时代,情感连接已成为品牌破圈的关键通道。我们在服务大量品牌客户的过程中发现,消费者对内容的“有感”程度,正日益成为影响品牌传播效率与转化率的核心变量。在生成式AI驱动的内容生成与推荐环境中࿰…...
三体问题详解
从物理学角度,三体问题之所以不稳定,是因为三个天体在万有引力作用下相互作用,形成一个非线性耦合系统。我们可以从牛顿经典力学出发,列出具体的运动方程,并说明为何这个系统本质上是混沌的,无法得到一般解…...
在WSL2的Ubuntu镜像中安装Docker
Docker官网链接: https://docs.docker.com/engine/install/ubuntu/ 1、运行以下命令卸载所有冲突的软件包: for pkg in docker.io docker-doc docker-compose docker-compose-v2 podman-docker containerd runc; do sudo apt-get remove $pkg; done2、设置Docker…...
vue3+vite项目中使用.env文件环境变量方法
vue3vite项目中使用.env文件环境变量方法 .env文件作用命名规则常用的配置项示例使用方法注意事项在vite.config.js文件中读取环境变量方法 .env文件作用 .env 文件用于定义环境变量,这些变量可以在项目中通过 import.meta.env 进行访问。Vite 会自动加载这些环境变…...
SAP学习笔记 - 开发26 - 前端Fiori开发 OData V2 和 V4 的差异 (Deepseek整理)
上一章用到了V2 的概念,其实 Fiori当中还有 V4,咱们这一章来总结一下 V2 和 V4。 SAP学习笔记 - 开发25 - 前端Fiori开发 Remote OData Service(使用远端Odata服务),代理中间件(ui5-middleware-simpleproxy)-CSDN博客…...
高效线程安全的单例模式:Python 中的懒加载与自定义初始化参数
高效线程安全的单例模式:Python 中的懒加载与自定义初始化参数 在软件开发中,单例模式(Singleton Pattern)是一种常见的设计模式,确保一个类仅有一个实例,并提供一个全局访问点。在多线程环境下,实现单例模式时需要注意线程安全问题,以防止多个线程同时创建实例,导致…...
