我有以下字符串:
"i like ??dogs? and cats"
我想识别子串??狗?并用其他东西替换它,让我们说#34;?鸟"。
所以我创建了这个函数:
function strUnderline (str, oldword, newword) {
str = str.replace(new RegExp('(^|[-,.!?:;"\'\(\\s])' + oldword + '(?=$|[-?!,.:;"\'\)\\s])'), "$1" + newword)
return str;
};
但是当我跑步时:
strUnderline("i like ??dogs? and cats", "??dogs?", "?birds")
我得到:
"i like ???birds? and cats"
我想定义单词边界并捕捉它们。
有什么建议吗?
答案 0 :(得分:2)
如果要替换oldWord
的所有匹配项,则需要转义问号:
function strUnderline(str, oldWord, newWord) {
oldWord = oldWord.replace(new RegExp(/\?/g), "\\?");
return str.replace(new RegExp(oldWord, 'g'), newWord);
}
let input = "i like ??dogs? and cats, but especially ??dogs?";
let output = strUnderline(input, "??dogs?", "?birds");
console.log(output);

对于更通用的正则表达式,它会逃避所有特殊字符,请阅读this。