示例 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 ", " has a ", " house and a ", " car"]。 - 数组元素使用
join()
方法连接成一个单一的字符串。
这里,reverseArray.join('blue')
通过连接数组元素得到 Mr blue has a blue house and a blue car。
另请阅读