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!

1 Answer 1

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"
}
Sign up to request clarification or add additional context in comments.

1 Comment

Awesome, that's exactly what I want. I'll accept it as soon as I can.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.