当前位置: 首页 > news >正文

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 注意事项
  1. 区分大小写indexOf() 是区分大小写的。如果需要不区分大小写的查找,可以先将字符串转换为统一大小写:

    const str = "Hello, world!";
    const index = str.toLowerCase().indexOf("world".toLowerCase());console.log(index); // 输出: 7
  2. 查找所有匹配项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]
  3. 与 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 注意事项
  1. 区分大小写lastIndexOf() 是区分大小写的。如果需要不区分大小写的查找,可以先将字符串转换为统一大小写:

    const str = "Hello, World! world!";
    const index = str.toLowerCase().lastIndexOf("world".toLowerCase());console.log(index); // 输出: 14
  2. 与 indexOf() 的区别

    • indexOf() 从字符串开头向后查找,返回第一次出现的位置。

    • lastIndexOf() 从字符串末尾向前查找,返回最后一次出现的位置。

  3. 查找所有匹配项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]
  4. 与 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 注意事项
  1. 区分大小写includes() 是区分大小写的。如果需要不区分大小写的查找,可以先将字符串转换为统一大小写:

    const str = "Hello, world!";
    const result = str.toLowerCase().includes("WORLD".toLowerCase());console.log(result); // 输出: true
  2. 与 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 注意事项
  1. 区分大小写startsWith() 是区分大小写的。如果需要不区分大小写的检查,可以先将字符串转换为统一大小写:

    const str = "Hello, world!";
    const result = str.toLowerCase().startsWith("hello".toLowerCase());console.log(result); // 输出: true
  2. 与 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 注意事项
  1. 区分大小写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 大于 endIndexslice() 会返回一个空字符串:

const str = "Hello, world!";
const result = str.slice(5, 2);console.log(result); // 输出: ""
console.log(str);    // 输出: "Hello, world!" (原字符串未改变)

1.6.6 总结
特性说明
是否改变原数据不会改变原字符串或数组。
返回值返回一个新的字符串或数组,包含提取的部分。
适用场景提取字符串或数组的一部分。

1.6.7 注意事项
  1. 负数索引slice() 支持负数索引,表示从末尾开始计算。

  2. 与 substring() 的区别

    • slice() 支持负数索引。

    • substring() 不支持负数索引,且会将负数索引视为 0。

  3. 与 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 大于 endIndexsubstring() 会自动交换两个参数:

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 注意事项
  1. 负数索引substring() 不支持负数索引。如果传递负数索引,会被视为 0。

  2. 与 slice() 的区别

    • slice() 支持负数索引。

    • substring() 不支持负数索引,且会将负数索引视为 0。

    • 如果 startIndex 大于 endIndexsubstring() 会自动交换两个参数,而 slice() 会返回空字符串。

  3. 与 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 注意事项
  1. 负数索引substr() 支持负数索引,表示从字符串末尾开始计算。

  2. 与 slice() 的区别

    • substr() 的第二个参数是提取的长度。

    • slice() 的第二个参数是结束索引(不包含)。

  3. 与 substring() 的区别

    • substr() 支持负数索引。

    • substring() 不支持负数索引,且会将负数索引视为 0。

  4. 遗留方法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 注意事项
  1. 与 + 操作符的区别

    • concat() 和 + 操作符的功能类似,都可以用于合并字符串。

    • + 操作符的性能通常优于 concat()

  2. 非字符串类型

    • concat() 会将非字符串类型的参数转换为字符串。

  3. 性能

    • 如果需要合并大量字符串,建议使用 + 操作符或模板字符串(`),因为它们的性能更好。

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 注意事项
  1. 替换第一个匹配项

    • 如果 searchValue 是字符串,replace() 只会替换第一个匹配项。

    • 如果需要替换所有匹配项,可以使用正则表达式并添加 g 标志。

  2. 正则表达式

    • 如果 searchValue 是正则表达式,可以使用捕获组和标志(如 gi 等)。

  3. 函数作为替换值

    • 如果 replaceValue 是函数,函数的参数依次为:

      • match:匹配的子字符串。

      • p1, p2, ...:捕获组的内容(如果有)。

      • offset:匹配的子字符串在原字符串中的偏移量。

      • string:原字符串。

  4. 特殊字符

    • 如果 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 注意事项
  1. 全局替换

    • replaceAll() 会替换所有匹配项,而不像 replace() 默认只替换第一个匹配项。

  2. 正则表达式

    • 如果 searchValue 是正则表达式,必须包含 g 标志,否则会抛出错误。

  3. 函数作为替换值

    • 如果 replaceValue 是函数,函数的参数依次为:

      • match:匹配的子字符串。

      • p1, p2, ...:捕获组的内容(如果有)。

      • offset:匹配的子字符串在原字符串中的偏移量。

      • string:原字符串。

  4. 特殊字符

    • 如果 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 注意事项
  1. 非字母字符

    • toLowerCase() 只会影响字母字符,非字母字符(如数字、标点符号)不会改变。

  2. Unicode 字符

    • toLowerCase() 支持 Unicode 字符,可以将大写字母(如 ÄÖÜ)转换为小写形式(如 äöü)。

  3. 性能

    • 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 注意事项
  1. 非字母字符

    • toUpperCase() 只会影响字母字符,非字母字符(如数字、标点符号)不会改变。

  2. Unicode 字符

    • toUpperCase() 支持 Unicode 字符,可以将小写字母(如 äöü)转换为大写形式(如 ÄÖÜ)。

  3. 性能

    • 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 注意事项
  1. 空白字符

    • trim() 会去除所有空白字符,包括空格、制表符(\t)、换行符(\n)等。

  2. 中间空白字符

    • trim() 不会去除字符串中间的空白字符。

  3. 兼容性

    • 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 注意事项
  1. 空白字符

    • trimStart() 会去除所有空白字符,包括空格、制表符(\t)、换行符(\n)等。

  2. 中间和结尾空白字符

    • trimStart() 不会去除字符串中间和结尾的空白字符。

  3. 兼容性

    • 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 注意事项
  1. 空白字符

    • trimEnd() 会去除所有空白字符,包括空格、制表符(\t)、换行符(\n)等。

  2. 开头和中间空白字符

    • trimEnd() 不会去除字符串开头和中间的空白字符。

  3. 兼容性

    • 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 注意事项
  1. 分隔符

    • 如果 separator 是空字符串,split() 会将字符串拆分为单个字符的数组。

    • 如果 separator 未找到,split() 会返回包含原字符串的数组。

  2. 正则表达式

    • 如果 separator 是正则表达式,split() 会根据正则表达式的匹配结果拆分字符串。

  3. 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 注意事项
  1. 索引范围

    • 如果 index 为负数或大于等于字符串长度,charAt() 会返回空字符串。

  2. 与 [] 访问符的区别

    • 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 注意事项
  1. 索引范围

    • 如果 index 为负数或大于等于字符串长度,charCodeAt() 会返回 NaN

  2. 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 注意事项
  1. 编码范围

    • fromCharCode() 只能处理 0 到 65535 之间的 Unicode 编码。

    • 对于超出 BMP 的字符(如表情符号),需要使用代理对。

  2. 与 codePointAt() 的关系

    • codePointAt() 用于获取字符的完整 Unicode 编码。

    • fromCharCode() 用于将 Unicode 编码转换为字符。

  3. 与 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 注意事项
  1. 全局匹配

    • 如果正则表达式包含 g 标志,match() 会返回所有匹配项的数组。

    • 如果不包含 g 标志,match() 会返回第一个匹配项的详细信息(包括捕获组)。

  2. 捕获组

    • 如果正则表达式包含捕获组,match() 会返回捕获组的内容。

  3. 与 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 注意事项
  1. 全局匹配

    • search() 会忽略正则表达式中的 g 标志,只返回第一个匹配项的索引。

  2. 捕获组

    • search() 会忽略正则表达式中的捕获组,只返回第一个匹配项的索引。

  3. 与 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 注意事项
  1. 参数范围

    • count 必须是非负整数。

    • 如果 count 是小数,会向下取整。

    • 如果 count 为负数或无效参数,会抛出错误。

  2. 性能

    • 如果 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​ 模块提供了开箱即用的缓存抽象,但如何根据业务需求实现灵活、可靠的缓存方案&#xf…...

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…...

机器视觉运动控制一体机在天地盖同步跟随贴合解决方案

市场应用背景 纸盒天地盖是一种包装形式,广泛应用于消费电子、食品礼盒、奢侈品及化妆品等领域。其采用高强度纸板,经过预组装处理,结构坚固稳定,能有效保护产品并提升品牌形象。随着包装行业快速发展,市场对天地盖的…...

贪心算法一

> 作者:დ旧言~ > 座右铭:松树千年终是朽,槿花一日自为荣。 > 目标:了解什么是贪心算法,并且掌握贪心算法。 > 毒鸡汤:有些事情,总是不明白,所以我不会坚持。早安! >…...

1688商品列表API与其他数据源的对接思路

将1688商品列表API与其他数据源对接时,需结合业务场景设计数据流转链路,重点关注数据格式兼容性、接口调用频率控制及数据一致性维护。以下是具体对接思路及关键技术点: 一、核心对接场景与目标 商品数据同步 场景:将1688商品信息…...

零基础设计模式——行为型模式 - 责任链模式

第四部分:行为型模式 - 责任链模式 (Chain of Responsibility Pattern) 欢迎来到行为型模式的学习!行为型模式关注对象之间的职责分配、算法封装和对象间的交互。我们将学习的第一个行为型模式是责任链模式。 核心思想:使多个对象都有机会处…...

学校时钟系统,标准考场时钟系统,AI亮相2025高考,赛思时钟系统为教育公平筑起“精准防线”

2025年#高考 将在近日拉开帷幕,#AI 监考一度冲上热搜。当AI深度融入高考,#时间同步 不再是辅助功能,而是决定AI监考系统成败的“生命线”。 AI亮相2025高考,40种异常行为0.5秒精准识别 2025年高考即将拉开帷幕,江西、…...

【Java学习笔记】BigInteger 和 BigDecimal 类

BigInteger 和 BigDecimal 类 二者共有的常见方法 方法功能add加subtract减multiply乘divide除 注意点:传参类型必须是类对象 一、BigInteger 1. 作用:适合保存比较大的整型数 2. 使用说明 创建BigInteger对象 传入字符串 3. 代码示例 import j…...

站群服务器的应用场景都有哪些?

站群服务器主要是为了多个网站的托管和管理所设计的,可以通过集中管理和高效资源的分配,来支持多个独立的网站同时运行,让每一个网站都可以分配到独立的IP地址,避免出现IP关联的风险,用户还可以通过控制面板进行管理功…...

在鸿蒙HarmonyOS 5中使用DevEco Studio实现企业微信功能

1. 开发环境准备 ​​安装DevEco Studio 3.1​​: 从华为开发者官网下载最新版DevEco Studio安装HarmonyOS 5.0 SDK ​​项目配置​​: // module.json5 {"module": {"requestPermissions": [{"name": "ohos.permis…...

Python网页自动化Selenium中文文档

1. 安装 1.1. 安装 Selenium Python bindings 提供了一个简单的API,让你使用Selenium WebDriver来编写功能/校验测试。 通过Selenium Python的API,你可以非常直观的使用Selenium WebDriver的所有功能。 Selenium Python bindings 使用非常简洁方便的A…...

uni-app学习笔记三十五--扩展组件的安装和使用

由于内置组件不能满足日常开发需要,uniapp官方也提供了众多的扩展组件供我们使用。由于不是内置组件,需要安装才能使用。 一、安装扩展插件 安装方法: 1.访问uniapp官方文档组件部分:组件使用的入门教程 | uni-app官网 点击左侧…...

验证redis数据结构

一、功能验证 1.验证redis的数据结构(如字符串、列表、哈希、集合、有序集合等)是否按照预期工作。 2、常见的数据结构验证方法: ①字符串(string) 测试基本操作 set、get、incr、decr 验证字符串的长度和内容是否正…...

基于Uniapp的HarmonyOS 5.0体育应用开发攻略

一、技术架构设计 1.混合开发框架选型 (1)使用Uniapp 3.8版本支持ArkTS编译 (2)通过uni-harmony插件调用原生能力 (3)分层架构设计: graph TDA[UI层] -->|Vue语法| B(Uniapp框架)B --&g…...