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:

javascriptlet str = 'img.png';

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

javascriptlet 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:

javascriptlet 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:

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

Now we insert a variable using template strings:

javascriptlet 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:

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

Practical tasks

Задание 1

Put the names of domain zones into a separate variable:

javascriptlet reg = /^[a-z]+\.(ru|by|ua)$/;
let res = reg.test(str);
Задание 2

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

javascriptlet arr = ['ru', 'by', 'ua'];