简体   繁体   English

在 Javascript 的正则表达式中包含变量

[英]Including variable inside regex in Javascript

I have this ReGex string to catch anything that starts with go/ in a sentence:我有这个正则表达式字符串来捕捉任何以go/开头的句子:

/\bgo/i

It works great.它工作得很好。 However, the word go can change so I want to include a variable inside it so I moved it to RegExp like so:但是,单词go可以更改,因此我想在其中包含一个变量,因此我将其移至RegExp ,如下所示:

const variable = 'go';
const rex = new RegExp(`/\b${variable}/`, 'i');`

However, it doesn't seem to work, I'm not sure why.但是,它似乎不起作用,我不知道为什么。 I even tried removing the start/end sequence characters but it still doesn't work.我什至尝试删除开始/结束序列字符,但它仍然不起作用。

I think you want this:我想你想要这个:

const rex = new RegExp(`\\b${variable}/`, 'i')

When using the RegExp constructor, you don't want to include the / at the start and end that would be on a literal regex like:使用RegExp构造函数时,您不想在开头和结尾包含/ ,这将在文字正则表达式上,例如:

const rex = /foo/

Those / is just the regex literal syntax and not part of the regex content.那些/只是正则表达式文字语法,而不是正则表达式内容的一部分。 Though you do seem to want an actual trailing / , so that stays.尽管您似乎确实想要一个实际的尾随/ ,但它仍然存在。

Second, you have to double escape the backslash of \b as \\b .其次,您必须将\b的反斜杠双重转义为\\b This is because in a normal string literal the backslash escapes the next character.这是因为在普通字符串文字中,反斜杠会转义下一个字符。 In this case the b .在这种情况下, b But you want the backslash in your regex, so you have to escape the backslash, with a backslash.但是你想要你的正则表达式中的反斜杠,所以你必须用反斜杠转义反斜杠。

 const variable = 'go' const rex = new RegExp(`\\b${variable}/`, 'i') console.log('regex:', rex) // shows the regex that was created console.log(rex.test('go/'))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM