只要您有一个已知模式(即您不使用变量来构建 RegExp),请使用文字正则表达式表示法,您只需要使用单个反斜杠来转义特殊的正则表达式元字符:
var re = /I like your Apartment\. Could we schedule a viewing\?/g;
^^ ^^
每当您需要动态构建 RegExp 时,请使用RegExp
构造函数表示法,其中您必须使用双反斜杠来表示文字反斜杠:
var questionmark_block = "\\?"; // A literal ?
var initial_subpattern = "I like your Apartment\\. Could we schedule a viewing"; // Note the dot must also be escaped to match a literal dot
var re = new RegExp(initial_subpattern + questionmark_block, "g");
如果您使用String.raw
字符串文字,您可以\
按原样使用(请参阅使用模板字符串文字的示例,您可以将变量放入正则表达式模式):
const questionmark_block = String.raw`\?`; // A literal ?
const initial_subpattern = "I like your Apartment\\. Could we schedule a viewing";
const re = new RegExp(`${initial_subpattern}${questionmark_block}`, 'g'); // Building pattern from two variables
console.log(re); // => /I like your Apartment\. Could we schedule a viewing\?/g
必读:RegExp: MDN 上的描述。