I have a string which contains multiple words. I have a phrase that should be replaced. However, there are multiple very similar phrases that should be replaced.
Here are strings that should be replaced (removed):
- "fox jumps over the lazy dog"
- "fox jumps over the lazy cat"
- "fox jumpa over the lazy cat"
- "fox jumpaoverthe lazy cat" (meaning there could be missing spaces between words)
case insensitive, global
var str = "The quick brown fox jumpa over the lazy dog";
// result would be "The quick brown "str = "The quick brown fox jump over the lazy dog";
// result would be "The quick brown "str = "The quick brown fox jump over the lazy cat";
// result would be "The quick brown "str = "The quick brown fox jumpa over the lazy cat";
// result would be "The quick brown "str = "The quickbrownfoxjumpaoverthe lazy cat";
// result would be "The quick brown "
My try doesn't work:
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
Answer
You can use the following regex : 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
No comments:
Post a Comment