跳到主要内容

JavaScript 程序:替换字符串的所有出现

要理解这个示例,你应该具备以下 JavaScript 编程 主题的知识:

示例 1:使用正则表达式替换字符串中所有出现的内容

// 程序替换字符串中所有出现的内容

const string = "Mr Red has a red house and a red car";

// 正则表达式
const regex = /red/gi;

// 替换字符
const newText = string.replace(regex, "blue");

// 显示结果
console.log(newText);

输出

Mr blue has a blue house and a blue car

在上述程序中,使用正则表达式作为 replace() 方法的第一个参数。

/g 表示全局(替换整个字符串中的内容),/i 表示不区分大小写。

replace() 方法将你想要替换的字符串作为第一个参数,将你想要替换成的字符串作为第二个参数。

示例 2:使用内置方法替换字符串中所有出现的内容

// 程序替换字符串中所有出现的内容

const string = "Mr red has a red house and a red car";

const result = string.split("red").join("blue");

console.log(result);

输出

Mr blue has a blue house and a blue car

在上述程序中,使用了内置的 split()join() 方法来替换字符串中所有出现的内容。

  • 使用 split() 方法将字符串分割成单独的数组元素。 这里,string.split('red') 通过分割字符串得到 ["Mr ", " has a ", " house and a ", " car"]。
  • 使用 join() 方法将数组元素连接成单个字符串。 这里,reverseArray.join('blue') 通过连接数组元素得到 Mr blue has a blue house and a blue car。