⊗jsSpOptRg 276 of 294 menu

Optimizing the use of regexes in JavaScript

Regular expressions are very heavy and relatively slow working thing. When there is an alternative solution, it is preferable to use it.

Let's look at an example. Suppose we need to check if some string starts with an exclamation mark. A programmer solved this problem using a regex:

let str = '!123'; if (/^!/.test(str)) { console.log('+++'); } else { console.log('---'); }

However, this problem has a much faster solution:

let str = '!123'; if (str[0] == '!') { console.log('+++'); } else { console.log('---'); }

The following code checks for the presence of the substring '33' in a string. Perform optimization:

let str = '123345'; if (/33/.test(str)) { console.log('+++'); } else { console.log('---'); }

The following code checks if a string ends with '.html'. Perform optimization:

let str = 'index.html'; if (/\.html$/.test(str)) { console.log('+++'); } else { console.log('---'); }

The following code trims trailing spaces. Perform optimization:

let str = ' text '; let res = str.replace(/^\s+|\s+$/g, ''); console.log(res);
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