renathy
renathy

Reputation: 5355

Javascript regexp: replace this or that word (have or not whitespaces between words)

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):

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

Upvotes: 0

Views: 73

Answers (1)

Hassan Imam
Hassan Imam

Reputation: 22534

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

Upvotes: 2

Related Questions