Nick Gl
Nick Gl

Reputation: 119

How to set variable-template in the regular expression?

There is a file extension pattern:

const pattern = '.js';

How correctly to set a template, to make regex work?

const reg = /(.*\pattern$)/;

Upvotes: 0

Views: 238

Answers (1)

CRice
CRice

Reputation: 32176

Use the regex constructor. Link to docs.

For your snippet:

const pattern = '.js';
const reg = new RegExp(`(.*${pattern}$)`);

This has the caveat that you have to double escape your backslashes (the first one escapes it in the string, so that the second actually makes it into the regex). I'm assuming the one present in the example was a part of your attempt to put the pattern in there, but if not then it should be

new RegExp(`(.*\\${pattern}$)`)

Upvotes: 1

Related Questions