我有一个包含多个单词的字符串。我有一个短语应该被替换。但是,有多个非常相似的短语需要替换。
以下是应替换(删除)的字符串:
- “狐狸跳过懒狗”
- “狐狸跳过懒猫”
- “狐狸跳过懒猫”
- “狐狸跳越懒猫”(意思是单词之间可能缺少空格)
不区分大小写,全局
var str = "敏捷的棕色狐狸跳过了懒狗"; //结果将是“快速棕色”
str = "敏捷的棕色狐狸跳过了懒狗"; //结果将是“快速棕色”
str = "敏捷的棕色狐狸跳过了懒猫"; //结果将是“快速棕色”
str = "敏捷的棕色狐狸跳过了懒猫"; //结果将是“快速棕色”
str = "快棕狐跳越懒猫"; //结果将是“快速棕色”
我的尝试不起作用:
let str1 = "The quick brown fox jumpa overthe lazy cat";
let reg = /The\s*quick\s*brown\s*fox\s*jump[s|a]\s*over\s*the\s*lazy [\bcat\b|\bdog\b]/gi;
let res = str1.replace(reg, "");
console.log(res); //should be empty
str1 = "The quickbrownfox jumps overthe lazy cat";
res = str1.replace(reg, "");
console.log(res); //should be empty
最佳答案
您可以使用以下正则表达式:The\s*quick\s*brown\s*fox\s*jump(s|a)?\s*over\s*the\s*lazy\s*(cat|dog)/gi
let str1 = "The quick brown fox jumpa overthe lazy cat";
let reg = /The\s*quick\s*brown\s*fox\s*jump(s|a)?\s*over\s*the\s*lazy\s*(cat|dog)/gi;
let res = str1.replace(reg, "");
console.log(res); //should be empty
str1 = "The quickbrownfox jumps overthe lazy cat";
res = str1.replace(reg, "");
console.log(res); //should be empty
关于JavaScript 正则表达式 : replace this or that word (have or not whitespaces between words),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48560813/