Javascript replace 使用正则进行替换的代码示范

3 min read

可以使用正则表达式和replace方法来进行替换。下面是一个简单的示例代码:

const str = "The quick brown fox jumps over the lazy dog.";
const pattern = /quick|lazy|fox/gi;
const replacement = "dog";
const result = str.replace(pattern, replacement);
console.log(result); // "The dog brown dog jumps over the dog dog."

这里使用了一个正则表达式来匹配字符串中的"quick"、"lazy"和"fox",然后将它们替换为"dog"。注意,正则表达式使用了"g"和"i"修饰符,分别表示全局匹配和不区分大小写的匹配。