示例: 替换字符串中首次出现的字符
// program to replace a character of a string const string = 'Mr Red has a red house and a red car'; // replace the characters const newText = string.replace('red', 'blue'); // display the result console.log(newText);
输出
Mr Red has a blue house and a red car
在上面的程序中,
replace()
方法用于将指定的字符串替换为另一个字符串。
当在
replace()
方法中传递字符串时,它仅替换字符串的第一个实例。因此,如果字符串中有第二个匹配项,则不会被替换。
您还可以在
replace()
方法中传递一个正则表达式 (regex) 来替换字符串。
示例 2: 使用 RegEx 替换字符串的字符
// program to replace a character of a string const string = 'Mr Red has a red house and a red car'; // regex expression const regex = /red/g; // replace the characters const newText = string.replace(regex, 'blue'); // display the result console.log(newText);
输出
Mr Red has a blue house and a blue car
在上面的程序中,使用正则表达式作为
replace()
方法中的第一个参数。
/g
指的是全局。这意味着替换字符串中所有匹配的字符。
由于 JavaScript 区分大小写,R 和 r 被视为不同的值。
您也可以使用正则表达式使用
/gi
执行不区分大小写的替换,其中
i
表示不区分大小写。