Search code examples
javascripthtmlnode.jsregexvariables

How do I pass a variable into regex with Node js?


So basically, I have a regular expression which is

var regex1 = /10661\" class=\"fauxBlockLink-linkRow u-concealed\">([\s\S]*?)<\/a>/;

var result=text.match(regex1);
user_activity = result[1].replace(/\s/g, "")
console.log(user_activity);

What I'm trying to do is this

var number = 1234;
var regex1 = /${number}\" class=\"fauxBlockLink-linkRow u-concealed\">([\s\S]*?)<\/a>/;

but it is not working, and when I tried with RegExp, I kept getting errors.


Solution

  • You can build the regex string with templates and/or string addition and then pass it to the RegExp constructor. One key in doing that is to get the escaping correct as you need an extra level of escaping for backslashes because the interpretation of the string takes one level of backslash, but you need one to survive as it gets to the RegExp contructor. Here's a working example:

    function match(number, str) {
        let r = new RegExp(`${number}" class="fauxBlockLink-linkRow u-concealed">([\\s\\S]*?)<\\/a>`);
        return str.match(r);
    }
    
    
    const exampleHTML = '<a href="something" class="aaa1234" class="fauxBlockLink-linkRow u-concealed">Some link text</a>';
    
    console.log(match(1234, exampleHTML));

    Note, using regex to match HTML like this becomes very order-sensitive (whereas the HTML itself isn't order-sensitive). And, your regex requires exactly one space between classes which HTML doesn't. If the class names were in a slightly different order or spacing different in the <a> tag, then it would not match. Depending upon what you're really trying to do, there may be better ways to parse and use the HTML that isn't order-sensitive.