Introduction to Regular Expressions in JavaScript

Regular expressions (regex or regexp) are such commands for complex search and replace (or just search). They allow you to do very interesting things, but, unfortunately, are quite difficult to master.

There are several JavaScript methods for working with regular expressions. We will start getting acquainted with them using the replace example - you are already familiar with this method: it takes what you need to replace as the first parameter, and by what as the second. And the method itself is applied to the string in which the replacement is performed:

'bab'.replace('a', '!'); // returns 'b!b'

You can pass not just a string as a first parameter of this method, but regular expression. A regular expression is a set of commands enclosed between the slashes /. These slashes are called delimiters of regular expressions.

Regular expressions themselves are made up of two types of characters: those denote themselves and command characters called special characters.

Letters and numbers denote themselves. In the following example, we will use a regular expression to replace the character 'a' with !:

'bab'.replace(/a/, '!'); // returns 'b!b'

But the dot is a special character and denotes any character. In the following example, we will find a string using a pattern like this: letter 'x', then any character, then again letter 'x':

'xax eee'.replace(/x.x/, '!'); // returns '! eee'

After the delimiters, you can write modifiers - commands that change the general properties of the regular expression. For example, the g modifier turns on the global search and replace mode, without it - the regex searches only for the first match, and all matches - with it.

In the following example, the g modifier is not specified and the regex will find only the first match:

'aab'.replace(/a/, '!'); // returns '!ab'

And now the regex will find all matches:

'aab'.replace(/a/g, '!'); // returns '!!b'

Given a string:

let str = 'ahb acb aeb aeeb adcb axeb';

Write a regex that matches the 'ahb', 'acb', 'aeb' strings using the pattern: letter 'a', any character, letter 'b'.

Given a string:

let str = 'aba aca aea abba adca abea';

Write a regex that matches the 'abba', 'adca', 'abea' strings using the pattern: letter 'a', any 2 characters, letter 'a'.

Given a string:

let str = 'aba aca aea abba adca abea';

Write a regex that matches the 'abba' and 'abea' strings without capturing 'adca'.

enru