Escaping is not exactly the term to describe what is happening in this scenario.
When creating a RegEx with an inline definition, it becomes tricky (without a backslash) to include a forward slash at the beginning of the expression because the double slash might be seen as a comment.
let re = //abc/g;
This is where new RegExp()
becomes useful. By providing the function with a string, it will form a RegEx without actually interpreting the contents.
Hence, the visuals in the console do not indicate escaping, but rather display two types of slashes consecutively:
- The outer slashes indicating the RegEx, followed by
- The inner slashes within your encapsulated string.
Unless you resort to using eval()
, there is no straightforward method to define a regular expression using a string where the slashes signify its boundaries. It is advised to avoid using eval()
.
To achieve the desired outcome, the easiest approach is to remove the initial and concluding characters of the string being passed in like this:
const re = new RegExp(config.regEx.slice(1,-1));
If you wish to conditionally eliminate the slashes, you could humorously utilize a regular expression:
const TRIM_SLASH = new RegExp('^/(.*)/$');
let stripped = config.regEx.replace(TRIM_SLASH,'$1');
const re = new RegExp(stripped);