简体   繁体   中英

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.

The only thing that was an actual issue with your code, though, was the \\b character class. This sequence is what you want RegExp to see, but you can't just write that, otherwise you're sending RegExp the backspace character .
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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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