1

This post details how to include variables in regular expressions, but it only shows how to include one variable. I am currently using the match function for a regular expression to find the string in between a leading and trailing string. My code is below:

array = text.match(/SomeLeadingString(.*?)SomeTrailingString/g);

Now, how could I construct a regular expression that has the same functionality as this, but rather than having the two strings I'm using actually in the expression, I would like to be able to create them outside, like so:

var startString = "SomeLeadingString"
var endString = "SomeTrailingString"

So, my final question is, how can I include startString and endString into the regular expression that I listed above so that the functionality is the same? Thanks!

Community
  • 1
  • 1
Alex Wulff
  • 2,039
  • 3
  • 18
  • 29

1 Answers1

3

Use RegExp object to concatenate strings to regex

const reg = new RegExp(`${startString}(\\w+)${endString}`,"g");
const matches = text.match(reg);

Note

When concatenating string, it is recommended to escape the none regex string: (the escape pattern is taken from this answer)

const escapeReg = (str)=>str.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');

Example

We have the string (.*)hello?? and we want to match the word between the (.*) and ??

we will do something like:

const prefix = "(.*)";
const suffix = "??";
const reg = new RegExp(`${escapeReg(prefix)}(\\w+)${escapeReg(suffix)}`);
const result = "(.*)hello??".match(reg);
if(result){
   console.log(result[1]); //"hello"
}
Daniel Krom
  • 9,751
  • 3
  • 43
  • 44