js基础回顾 replace 和 正则

176 阅读2分钟

replace 方法的参数

String.prototype.replace 方法用于替换字符串中的匹配内容。它可以接收两个参数:

  1. 第一个参数:匹配模式

    • 可以是一个字符串:直接匹配该字符串。
    • 可以是一个正则表达式:匹配符合正则表达式的内容。
  2. 第二个参数:替换内容

    • 可以是一个字符串:用于替换匹配到的内容。
    • 可以是一个回调函数:动态生成替换内容。

示例

// 使用字符串作为匹配模式

console.log('hello world'.replace('world''JavaScript')); 

// 输出: "hello JavaScript"

// 使用正则表达式作为匹配模式

console.log('hello world'.replace(/world/'JavaScript')); 

// 输出: "hello JavaScript"

// 使用回调函数作为替换内容

console.log('hello world'.replace(/(world)/(match) => match.toUpperCase())); 

// 输出: "hello WORLD"

replace 回调函数的参数

当 replace 的第二个参数是回调函数时,回调函数会接收以下参数:

  1. match:匹配到的子字符串。
  2. p1, p2, ... :正则表达式中的捕获组(如果有)。
  3. offset:匹配到的子字符串在原字符串中的索引。
  4. string:被匹配的原字符串。

示例


const str = 'color: red; backgroundColor: blue;';

const result = str.replace(/([A-Z])/g(match, p1, offset, string) => {

    console.log(`Match: ${match}, Captured: ${p1}, Offset: ${offset}, String: ${string}`);

    return `-${p1.toLowerCase()}`;

});

console.log(result);

// 输出:

// Match: C, Captured: C, Offset: 13, String: color: red; backgroundColor: blue;

// color: red; background-color: blue;

正则校验的几个方法

正则表达式在 JavaScript 中有多种方法可以用来匹配和操作字符串:

  1. test

    • 用于测试字符串是否匹配正则表达式。
    • 返回布尔值。
    const regex = /hello/;

    console.log(regex.test('hello world')); // true
  1. exec

    • 用于匹配字符串,返回第一个匹配结果的详细信息(数组形式)。
    • 如果没有匹配到,返回 null
    const regex = /hello/;
    
    console.log(regex.exec('hello world')); 
    // ["hello", index: 0, input: "hello world"]
  1. match

    • 用于从字符串中提取匹配结果。
    • 返回一个数组,包含所有匹配的内容。
    const str = 'hello world';

    console.log(str.match(/hello/)); // ["hello", index: 0input"hello world"]
  1. replace

    • 用于替换匹配的内容。
    • 返回替换后的新字符串。
    const str = 'hello world';

    console.log(str.replace(/world/'JavaScript')); // "hello JavaScript"
  1. split

    • 用于根据正则表达式分割字符串。
    • 返回一个数组。
    const str = 'hello world';

    console.log(str.split(/\s/)); // ["hello", "world"]

区别总结

  • test:快速判断是否匹配,返回布尔值。
  • exec:获取匹配的详细信息,适合需要捕获组的场景。
  • match:从字符串中提取匹配内容,适合简单提取。
  • replace:替换匹配内容,支持动态替换。
  • split:根据正则分割字符串。