String with a regex in JavaScript

Regular expressions can be represented as strings. This is convenient if you need to insert variables into regexes, or create them dynamically.

Let's look at an example. Let's say we have the following string:

let str = 'img.png';

Let's apply the following regular expression to this string:

let reg = /\.(png|jpg)$/; let res = str.match(reg);

Let's rewrite this regular expression as a string. This is done using the special RegExp object:

let reg = new RegExp('\.(png|jpg)$'); let res = str.match(reg);

Let's now put a part of the regex into a variable and insert it using concatenation:

let pat = 'png|jpg'; let reg = new RegExp('\.(' + pat + ')$'); let res = str.match(reg);

Now we insert a variable using template strings:

let pat = 'png|jpg'; let reg = new RegExp(`\.(${pat})$`); let res = str.match(reg);

And now we create a part of the regex from an array:

let exts = ['png', 'jpg']; let pat = exts.join('|') let reg = new RegExp(`\.(${pat})$`); let res = str.match(reg);

Practical tasks

Put the names of domain zones into a separate variable:

let reg = /^[a-z]+\.(ru|by|ua)$/; let res = reg.test(str);

Modify the previous task to take into account that domain zones are stored as an array:

let arr = ['ru', 'by', 'ua'];
enru