假设我有字符串变量:
var animals = "catdog caT dog cat";
我不想要猫、大猫和凌乱的空白。我尝试过使用:
var rep = "cat"
var nocats = animals.replace(new RegExp(rep, 'g'), '');
nocats 现在是“狗猫狗”,而我需要“猫狗狗”
我应该使用什么正则表达式?
最佳答案
使用 \b
作为字边界和不区分大小写(i
标志)正则表达式:
var animals = "catdog caT dog cat",
animal = "cat"
animals.replace(new RegExp("\\b" + animal + "\\b", "gi"), "");
// "catdog dog " needs additional trimming
关于javascript - 如何使用 javascript 正则表达式进行清理 - 不区分大小写 + 空格 + 整个单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12076018/