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