replace方法

我们来详细解释 JavaScript 中 String.prototype.replace() 方法。

replace() 方法详解

replace() 方法用于在字符串中查找指定的内容(可以是子字符串或正则表达式),并将其替换为新的内容,然后返回一个的字符串。原字符串不会被修改。

语法

vbscript 复制代码
str.replace(regexp|substr, newSubstr|function)
  • str: 调用 replace 方法的源字符串。

  • regexp | substr: 指定要查找的内容。

    • regexp (正则表达式): 一个正则表达式对象,或者一个包含正则表达式的字符串。如果 regexp 具有全局标志 g,则会替换所有匹配项;否则,只替换第一个匹配项。
    • substr (字符串): 要被替换的字符串。只会替换第一个匹配的子串。
  • newSubstr | function: 指定要替换为的内容。

    • newSubstr (字符串): 新的字符串,用来替换查找到的内容。
    • function (替换函数): 一个函数,它的返回值将被用来替换匹配项。

1. 使用字符串 substr 作为查找目标

当第一个参数是字符串时,replace 只会替换第一次出现的匹配项。

ini 复制代码
let str = "hello world hello universe";
let newStr = str.replace("hello", "hi");
console.log(newStr); // 输出: "hi world hello universe"
console.log(str);    // 输出: "hello world hello universe" (原字符串不变)

2. 使用正则表达式 regexp 作为查找目标

这是更强大和常用的方式,因为它提供了模式匹配的能力。

  • 不带 g 标志: 只替换第一个匹配项。
  • g 标志 (global) : 替换所有匹配项。

示例 1: 不带 g 标志

ini 复制代码
let str = "hello world hello universe";
let newStr = str.replace(/hello/, "hi"); // 正则表达式 /hello/
console.log(newStr); // 输出: "hi world hello universe"

示例 2: 带 g 标志

ini 复制代码
let str = "hello world hello universe";
let newStr = str.replace(/hello/g, "hi"); // /hello/g 匹配所有 "hello"
console.log(newStr); // 输出: "hi world hi universe"

3. 使用字符串作为 newSubstr (替换内容)

这是最常见的替换方式,直接用一个固定的字符串替换匹配的部分。

ini 复制代码
let str = "The quick brown fox jumps over the lazy dog.";
let newStr = str.replace(/brown/g, "red");
console.log(newStr); // 输出: "The quick red fox jumps over the lazy dog."

newSubstr 中使用特殊模式:

在替换字符串中,可以使用一些特殊的 $ 符号序列来插入匹配信息:

  • $$: 插入一个美元符号 $
  • $&: 插入匹配到的子串。
  • $ ``: 插入匹配子串之前的文本。
  • $ ': 插入匹配子串之后的文本。
  • $ n: 插入第 n 个捕获组的内容(n 是两位数字,如 $01, $02... $99)。
  • $ Nn: 插入第 N 个捕获组的内容(N 是一位数字,n 是一位数字,用于区分 N N 和 NN 和 NN和Nn)。

示例: 使用 $ &

ini 复制代码
let str = "abc def ghi";
let newStr = str.replace(/def/g, "($&)"); // $& 代表匹配到的 "def"
console.log(newStr); // 输出: "abc (def) ghi"

4. 使用函数作为 function (替换函数)

当需要动态生成替换内容时,使用替换函数非常有用。函数会被调用,每次匹配时都会执行,并接收特定的参数。

语法:

php 复制代码
function replacementFunction(match, p1, p2, ..., pN, offset, string) {
  // match: 匹配到的子串
  // p1, p2, ..., pN: 匹配到的捕获组 (如果正则表达式中有括号)
  // offset: 匹配到的子串在原字符串中的索引位置
  // string: 原始字符串
  // 返回值: 用于替换的字符串
}

示例: 将数字翻倍

javascript 复制代码
let str = "There are 3 cats and 5 dogs.";
let newStr = str.replace(/\d+/g, function(match) {
  // match 是匹配到的数字字符串 ("3", "5")
  return parseInt(match) * 2; // 转换为数字,翻倍,再转回字符串
});
console.log(newStr); // 输出: "There are 6 cats and 10 dogs."

示例: 使用捕获组

javascript 复制代码
let str = "John Smith, Jane Doe";
// 正则表达式 (\w+) (\w+) 捕获姓和名
let newStr = str.replace(/(\w+) (\w+)/g, function(match, firstName, lastName) {
  // match: "John Smith", "Jane Doe"
  // firstName: "John", "Jane"
  // lastName: "Smith", "Doe"
  return lastName + ", " + firstName; // 交换顺序
});
console.log(newStr); // 输出: "Smith, John, Doe, Jane"
相关推荐
EthanChou2020几秒前
AES67协议笔记
前端·笔记·es6
马优晨2 分钟前
pom.xml 中 jquery webjars 依赖解释
xml·前端·jquery·jquery webjars·webjars依赖
里欧跑得慢17 分钟前
AI 驱动的 UI 国际化方案自动适配:从单一语言到多语言布局的智能转换
前端·css·flutter·web
DolitD18 分钟前
云流技术深度剖析:单服务器下如何实现3D应用的多实例并发?
java·服务器·前端·3d·云原生·云计算
芦柑46425 分钟前
画布和3D导演台工具:短剧分镜从素材整理到空间预演的完整链路
服务器·前端·数据库
李蚊子39 分钟前
从代理提醒到真实响铃:懒熊闹钟的鸿蒙开发实践
前端·harmonyos
IT_陈寒1 小时前
Redis的Lua脚本居然把我的集群搞崩了!
前端·人工智能·后端
计算机魔术师1 小时前
索尼与华纳起诉Anthropic,指控其大规模盗用版权音乐训练Claude
前端
恋猫de小郭1 小时前
AI 时代,一个优化 Flutter 的重复代码工具 Deslop
android·前端·flutter
穗余1 小时前
Typescript let和var区别
前端·javascript·typescript