示例 1: 使用 RegEx 替换所有出现的字符串
// program to replace all occurrence of a string const string = 'Mr Red has a red house and a red car'; // regex expression const regex = /red/gi; // replace the characters const newText = string.replace(regex, 'blue'); // display the result console.log(newText);
输出
Mr blue has a blue house and a blue car
在上面的程序中,使用正则表达式作为
replace()
方法中的第一个参数。
/g
表示全局(替换是在整个字符串中完成的),
/i
表示不区分大小写。
replace()
方法将要替换的字符串作为第一个参数,将要替换的字符串作为第二个参数。
示例2: 使用内置方法替换所有出现的字符串
// program to replace all occurrence of a string 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 ", " 有一个 ", " house 和一个 ", " car"] 通过拆分字符串。
使用 join()
方法将数组元素连接成单个字符串。这里,
reverseArray.join('blue')
给出了 蓝色先生通过加入数组元素,拥有蓝色房子和蓝色汽车。