Hi everyone! I'm the author of code.mu :)
I'd love to chat with my non-Russian audience. I'm looking for your feedback on the site and the translation quality. Let's chat:)
⊗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, '!');
← →
↑
English▼
AfrikaansAzərbaycanБългарскиবাংলাБеларускаяČeštinaDanskDeutschΕλληνικάEspañolEestiSuomiFrançaisहिन्दीMagyarՀայերենIndonesiaItaliano日本語ქართულიҚазақ한국어КыргызчаLietuviųLatviešuМакедонскиMelayuမြန်မာNederlandsNorskPolskiPortuguêsRomânăРусскийසිංහලSlovenčinaSlovenščinaShqipСрпскиSrpskiSvenskaKiswahiliТоҷикӣไทยTürkmenTürkçeЎзбекOʻzbekTiếng Việt
We use cookies for website operation, analytics, and personalization. Data processing is carried out in accordance with the Privacy Policy.
accept all customize decline