# 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);`
←→
↑
en ru