JavaScript regexp模式中变量的一个奇怪问题

JavaScript regexp模式中变量的一个奇怪问题,javascript,Javascript,我想输入一个数字来查找,所以regexp模式必须是动态的,但我遇到了一些奇怪的问题 下面是示例代码: let list = ` [170] (50-20-3) Fant [173] (50-20-3) Chi [174] (50-20-3) Trib [176] (50-20-3) Fant [177] (50-20-3) Emo [178] (50-20-3) Fa `; // In fact, this 'find' variable is origin by user input. le

我想输入一个数字来查找,所以regexp模式必须是动态的,但我遇到了一些奇怪的问题

下面是示例代码:

let list = `
[170] (50-20-3) Fant
[173] (50-20-3) Chi
[174] (50-20-3) Trib
[176] (50-20-3) Fant
[177] (50-20-3) Emo
[178] (50-20-3) Fa
`;

// In fact, this 'find' variable is origin by user input.
let find = 170;
let re = new RegExp("[" + find + "](.+)");
let found = list.match(re)[1];

document.write(found);
根据这个例子,我所期望的是:

 (50-20-3) Fant
然而,我实际上得到了:

70] (50-20-3) Fant

您需要在括号中加引号,因为字符串不是正则表达式,通过将其转换为正则表达式,第一个带引号的qoute将转换为引号,这将引用括号

正则表达式中的括号表示字符类

let list=`
[170](50-20-3)范特
[173](50-20-3)池
[174](50-20-3)Trib
[176](50-20-3)范特
[177](50-20-3)Emo
[178](50-20-3)Fa
`;
让find=170;
让re=newregexp(“\\[”+find+“\\]”)(.+”);
let found=list.match(re)[1];

console.log(找到)value type ----- ------------------ '\\[' string /\[/ regular expression