JavaScript String replaceAll()

replaceAll() 方法返回一个新字符串,其中模式的所有匹配项都已替换为替换项。

示例

const message = "ball bat";

// replace all occurrence of b with c let result = message.replaceAll('b', 'c');
console.log(result); // Output: call cat

replaceAll() 语法

replaceAll() 的语法是

str.replaceAll(pattern, replacement)

这里,str 是一个字符串。


replaceAll() 参数

replaceAll() 方法接受

  • pattern - 要替换的子字符串或 正则表达式
  • replacement - pattern 被此 replacement 替换(可以是字符串或 函数

replaceAll() 返回值

  • replaceAll() 方法返回一个新字符串,其中模式的所有匹配项都已替换为替换项。

注意: 没有全局("g")标志的 RegExp 将会抛出 TypeError


示例 1: 使用 replaceAll()

const text = "Java is awesome. Java is fun.";

// passing a string as the first parameter
let pattern = "Java"; let new_text = text.replaceAll(pattern, "JavaScript");
console.log(new_text); // passing a regex as the first parameter
pattern = /Java/g; new_text = text.replaceAll(pattern, "JavaScript");
console.log(new_text);

输出

JavaScript is awesome. JavaScript is fun
JavaScript is awesome. JavaScript is fun.

替换而不考虑大小写

replaceAll() 方法区分大小写。要执行不区分大小写的替换,您需要使用带有 i 开关(不区分大小写的搜索)的正则表达式。

示例 2: 不区分大小写的替换

const text = "javaSCRIPT JavaScript";

// all occurrences of javascript is replaced
let pattern = /javascript/gi; // case-insensitive and global search let new_text = text.replaceAll(pattern, "JS");
console.log(new_text); // JS JS

输出

JS JS

示例 3: 将函数作为替换项传递

您还可以将函数(而不是字符串)作为 replaceAll() 方法的第二个参数传递。

const text = "3.1415";

// generate a random digit between 0 and 9
function generateRandomDigit() {
  return Math.floor(Math.random() * 10);
}

// regex to match a digit
const pattern = /\d/g; const new_text = text.replaceAll(pattern, generateRandomDigit);
console.log(new_text);

输出

4.3518

当您运行此程序时,您可能会得到不同的输出。这是因为 text 中的第一个数字被替换为 09 之间的随机数字。


另请阅读

你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战