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)

通过掌握这些方法,可以更高效地处理字符串数据。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:/a/982272.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

Sass 模块化革命:深入解析 @use 语法,打造高效 CSS 架构

文章目录 前言use 用法1. 模块化与命名空间2. use 中 as 语法的使用3. as * 语法的使用4. 私有成员的访问5. use 中with默认值6. use 导入问题总结下一篇预告: 前言 在上一篇中,我们深入探讨了 Sass 中 import 语法的局限性,正是因为这些问题…

AI-Deepseek + PPT

01--Deepseek提问 首先去Deepseek问一个问题: Deepseek的回答: 在汽车CAN总线通信中,DBC文件里的信号处理(如初始值、系数、偏移)主要是为了 将原始二进制数据转换为实际物理值,确保不同电子控制单元&…

解锁前端表单数据的秘密旅程:从后端到用户选择!✨

😄 解锁前端表单数据的秘密旅程:从后端到用户选择!✨ 嘿,技术爱好者们!👋 你有没有在开发中遇到过这样的困惑:表单里的数据(比如图片附件、识别点 ID)从哪儿来的&#x…

【Linux】进程间通信 续

目录 管道的原理(匿名管道) 核心原理 站在内核的角度看管道的本质 接口 创建管道文件 代码示例 管道的特征 管道读写端的四种情况 管道的应用场景 命令行的管道。 使用管道实现进程池 初始化 控制子进程 退出 命名管道 命名管道的理解 …

宇树科技再落一子!天羿科技落地深圳,加速机器人创世纪

2025年3月5日,机器人行业龙头宇树科技(Unitree)在深圳再添新动作——全资子公司深圳天羿科技有限公司正式成立。这家注册资本10万元、法定代表人周昌慧的新公司,聚焦智能机器人研发与销售,标志着宇树科技在华南市场的战…

AI-Ollama本地大语言模型运行框架与Ollama javascript接入

1.Ollama Ollama 是一个开源的大型语言模型(LLM)平台,旨在让用户能够轻松地在本地运行、管理和与大型语言模型进行交互。 Ollama 提供了一个简单的方式来加载和使用各种预训练的语言模型,支持文本生成、翻译、代码编写、问答等多种…

SQLAlchemy系列教程:基本数据类型及自定义类型

在SQLAlchemy、Python SQL工具包和ORM中定义模型时,理解基本数据类型至关重要。本教程提供了在SQLAlchemy模型中有效使用内置基本类型的指南。 SQLAlchemy中的基本类型 SQLAlchemy支持一组与SQL数据库类型一致的基本数据类型。SQLAlchemy中的每种类型都为各种SQL类…

K8s The connection to the server 192.168.56.120:6443 was refused报错解决

虚拟机获取不到其他node节点的信息,通过使用docker ps -a 排查看到k8s的组件都是exited的状态,通过手动拉起docker 镜像id 起来之后,又变为exited的状态!!! 解决方法:重置k8s集群 使用 kubeadm…

随机树算法 自动驾驶汽车的路径规划 静态障碍物(Matlab)

随着自动驾驶技术的蓬勃发展,安全、高效的路径规划成为核心挑战之一。快速探索随机树(RRT)算法作为一种强大的路径搜索策略,为自动驾驶汽车在复杂环境下绕过静态障碍物规划合理路径提供了有效解决方案。 RRT 算法基于随机采样思想…

【实战 ES】实战 Elasticsearch:快速上手与深度实践-2.3.1 避免频繁更新(Update by Query的代价)

👉 点击关注不迷路 👉 点击关注不迷路 👉 点击关注不迷路 文章大纲 Elasticsearch数据更新与删除深度解析:2.3.1 避免频繁更新(Update by Query的代价)案例背景1. Update by Query的内部机制解析1.1 文档更…

Baklib内容中台赋能企业智管

内容中台构建全场景智管 现代企业数字化运营中,全域内容管理能力已成为核心竞争力。通过智能知识引擎驱动的内容中台架构,企业能够实现跨部门、多形态数据的统一归集与动态调度。以某制造企业为例,其利用中台系统将分散在CRM、ERP及内部文档…

今天来介绍和讨论 AGI(通用人工智能)

首先介绍,AGI(通用人工智能)是什么? AGI(Artificial General Intelligence,通用人工智能)指的是能够像人类一样理解、学习、推理和解决广泛任务的人工智能系统。与目前的AI不同,AGI可…

计算机毕业设计SpringBoot+Vue.js乐享田园系统(源码+文档+PPT+讲解)

温馨提示:文末有 CSDN 平台官方提供的学长联系方式的名片! 温馨提示:文末有 CSDN 平台官方提供的学长联系方式的名片! 温馨提示:文末有 CSDN 平台官方提供的学长联系方式的名片! 作者简介:Java领…

navicat导出postgresql的数据库结构、字段名、备注等等

1、执行sql语句 SELECT A.attnum AS "序号",C.relname AS "表名",CAST ( obj_description ( relfilenode, pg_class ) AS VARCHAR ) AS "表名描述",A.attname AS "字段名称",A.attnotnull as "是否不为null",(case when A…

FPGA开发,使用Deepseek V3还是R1(9):FPGA的全流程(详细版)

以下都是Deepseek生成的答案 FPGA开发,使用Deepseek V3还是R1(1):应用场景 FPGA开发,使用Deepseek V3还是R1(2):V3和R1的区别 FPGA开发,使用Deepseek V3还是R1&#x…

DeepSeek、Grok 和 ChatGPT 对比分析:从技术与应用场景的角度深入探讨

文章目录 一、DeepSeek:知识图谱与高效信息检索1. 核心技术2. 主要特点3. 应用场景4. 实际案例 二、Grok:通用人工智能框架1. 核心技术2. 主要特点3. 应用场景4. 实际案例 三、ChatGPT:聊天机器人与通用对话系统1. 核心技术2. 主要特点3. 应用…

三、0-1搭建springboot+vue3前后端分离-idea新建springboot项目

一、ideal新建项目1 ideal新建项目2 至此父项目就创建好了,下面创建多模块: 填好之后点击create 不删了,直接改包名,看自己喜欢 修改包名和启动类名: 打开ServiceApplication启动类,修改如下: …

快速生成viso流程图图片形式

我们在写详细设计文档的过程中总会不可避免的涉及到时序图或者流程图的绘制,viso这个软件大部分技术人员都会使用,但是想要画的好看,画的科学还是比较难的,现在我总结一套比较好的方法可以生成好看科学的viso图(图片格式)。主要思…

【前端基础】Day 9 PC端品优购项目

目录 1. 品优购项目规划 1.1 网站制作流程 1.2 品优购项目整体介绍 1.3 学习目的 1.4 开发工具以及技术栈 1.5 项目搭建工作 1.6 网站favicon图标 1.7 网站TDK三大标签SEO优化 2. 品优购首页制作 2.1 常见模块类命名 2.2 快捷导航shortcut制作 2.3 header制作 2.4…

仿mudou库one thread oneloop式并发服务器

项目gitee:仿muduo: 仿muduo 一:项目目的 1.1项目简介 通过咱们实现的⾼并发服务器组件,可以简洁快速的完成⼀个⾼性能的服务器搭建。 并且,通过组件内提供的不同应⽤层协议⽀持,也可以快速完成⼀个⾼性能应⽤服务器…