Home > Software engineering >  How do I pass a variable into regex with Node js?
How do I pass a variable into regex with Node js?

Time:05-09

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.

CodePudding user response:

You can use RegExp to create regexp from a string and use variables in that string.

var number = 1234;
var regex1 = new RegExp(`${number}aa`);

console.log("1234aa".match(regex1));

CodePudding user response:

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}" >([\\s\\S]*?)<\\/a>`);
    return str.match(r);
}


const exampleHTML = '<a href="something"  >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.

  • Related