简体   繁体   English

如何在 Javascript 的正则表达式中使用变量?

[英]How to use a variable within a regex in Javascript?

I have a regular expression and would like to put a variable inside it.我有一个正则表达式,并想在其中放入一个变量。 How do I do?我该怎么办?

My code is this:我的代码是这样的:

public regexVariable(vRegex: string, testSentences: Array<any> ) {
    const regex = new RegExp('/^.*\b(' + vRegex + ')\b.*$/');
    const filterSentece = testSentences.filter(result => {
        if (regex.test(result)) {
            return result
        })
}

你快到了,看看RegEx 构造函数

const regex = new RegExp('^.*\\b(' + vRegex + ')\\b.*$');
const regex = new RegExp(`^.*\\b(${vRegex})\\b.*$`);

You can use template literals ( ` , instead of " / ' ) to build strings that you can interpolate expresions into; no more oldschool + ing.您可以使用模板文字` ,而不是" / ' )来构建可以插入表达式的字符串;不再使用 oldschool + ing。

The only thing that was an actual issue with your code, though, was the \\b character class.但是,您的代码唯一存在实际问题的是\\b字符类。 This sequence is what you want RegExp to see, but you can't just write that, otherwise you're sending RegExp the backspace character .这个序列是您希望RegExp看到的,但您不能只写那个,否则您将向RegExp发送退格字符
You need to write \\\\b , which as you can see from that link, will make a string with a \\ and an ordinary b for RegExp to interpret .您需要编写\\\\b ,正如您从该链接中看到的那样,它将生成一个带有\\和普通b的字符串,以便RegExp进行解释

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

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