JavaScript正则表达式不匹配,但在使用联机编辑器时匹配-变量问题?

JavaScript正则表达式不匹配,但在使用联机编辑器时匹配-变量问题?,javascript,regex,Javascript,Regex,我假设它与使用变量有关,当我在线测试它时,我不使用变量,它可以工作。我没有用太多的正则表达式,所以我可能也在做一些愚蠢的事情 let home = 'testhome'; let currentHome = 'testhome (8)'; let re = new RegExp(home + ' \(\d+\)'); if (currentHome.match(re)) { //no match } else { // this is the code executed }

我假设它与使用变量有关,当我在线测试它时,我不使用变量,它可以工作。我没有用太多的正则表达式,所以我可能也在做一些愚蠢的事情

let home = 'testhome';
let currentHome = 'testhome (8)';
let re = new RegExp(home + ' \(\d+\)');

if (currentHome.match(re)) {
    //no match
} else {
    // this is the code executed
}

谢谢你的帮助。使用RegExp构造函数时,
currentHome

的括号中可能有多个数字。您应该转义转义字符本身,以形成正确的reg表达式


let re=new RegExp(home+'\\(\\d+\\))

让re=newregexp(home+'\\(\\d+\\))谢谢。工作正常。@user3238415欢迎:)