示例:替换字符串中的第一个字符出现
// 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()
方法中传递字符串时,它只替换字符串中的第一个匹配项。因此,如果字符串中有第二个匹配项,它将不会被替换。
您也可以将正则表达式(regex) 传递到 replace()
方法中以替换字符串。
示例 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
表示不区分大小写。