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"
相关推荐
一tiao咸鱼5 分钟前
Ai 相关 7月1日学习
前端·agent
DarkLONGLOVE6 分钟前
快速上手 Pinia!Vue3 极简状态管理使用教程
javascript·vue.js
mackbob13 分钟前
.eslintrc.js详细配置说明
javascript
梨子同志20 分钟前
HTML
前端
ZhengEnCi26 分钟前
Q06-导航按钮高级拟态玻璃效果构建完全指南
前端·css
Apifox1 小时前
Apifox 6 月更新|Apifox CLI 全面升级、导入导出优化、OAuth 2.0 支持自动刷新令牌
前端·后端·测试
CodingSpace1 小时前
TypeScript 装饰器
前端
宸翰1 小时前
解决 uni-app App 端 vue-i18n 占位符丢失:封装跨端可用的 tf 格式化方法
前端·vue.js·uni-app
systemPro1 小时前
光储充系统数据流全解析:PV / ESS / GRID 数据怎么流转,线损怎么算
前端
用户298698530142 小时前
在 React 中使用 JavaScript 将 Excel 转换为 PDF
javascript·react.js·webassembly