Regular Expressions and Variables

Hello, I have a question on regular expressions and variables. My understanding is that the way to assign a variable string to a regular expression is to use the RegExp object like so:

let strVar = "string";
let regex = new RegExp(strVar);

But where I am having trouble is in understanding how I would construct a regular expression that uses a variable-string but that also uses the end-of-string β€œ$” as in the following:

let regex = /string$/gm, where the "$" specifies position at end.

So, my question is: how do I use a variable string and the RegExp object to create a regex that also incorporates β€œ$” ?

Thanks for any input!

When you are creating a regular expression with RegExp, you want to include the tokens (such as $) in the pattern string and you can include flags (like g and m) as a paramter when you create the RegExp.

Reading through the MDN documentation might help.

1 Like

Thanks a lot! Documentation-reading can be tedious…

Solution:

let strVar = "string";
let regex = new RegExp(strVar+"$"); 

1 Like