⊗jsSpRESBs 136 of 294 menu

Backslash in regex strings in JavaScript

In strings with regexes, you need to escape (actually double) backslashes. Let's look at an example. Let's say we have the following string:

let str = 'xyz';

Let's say we have the following code with regex:

let reg = /\w+/; let res = str.match(reg);

Let's convert the regular expression to a string. In this case, we have a problem with the backslash:

let reg = new RegExp('\w+'); // doesn't work let res = str.match(reg);

To solve the problem, double the backslash:

let reg = new RegExp('\\w+'); // works let res = str.match(reg);

Practical tasks

Convert a regex to string:

let str = 'x1y x12y x123y'; let reg = /x\d+y/; let res = str.replace(reg, '!');

Convert a regex to string:

let str = 'x.y xay xby'; let reg = /x\.y/; let res = str.replace(reg, '!');

Convert a regex to string:

let str = 'x\\y'; let reg = /x\\y/; let res = str.replace(reg, '!');
ruderoenms