'OR' command in JavaScript regular expressions

In this lesson, we'll look at the '|' command, which is a more powerful variant of 'OR' than the [ ] command. This command allows you to split the regex into several parts. In this case, the desired can fall either under one part of the regex, or under another. Let's look at examples.

Example

In this example, the search pattern is: three letters 'a' or three letters 'b':

javascriptlet str = 'aaa bbb abb';
let res = str.replace(/a{3}|b{3}/g, '!');

As a result, the following will be written to the variable:

javascript'! ! abb'

Example

In this example, the search pattern is: three letters 'a' or letters 'b' one or more times:

javascriptlet str = 'aaa bbb bbbb bbbbb axx';
let res = str.replace(/a{3}|b+/g, '!');

As a result, the following will be written to the variable:

javascript'! ! ! ! axx'

Example

In this example, the search pattern is: one or more letters or three digits:

javascriptlet str = 'a ab abc 1 12 123';
let res = str.replace(/[a-z]+|\d{3}/g, '!');

As a result, the following will be written to the variable:

javascript'! ! ! 1 12 !'

Example

The vertical bar can divide the regex not only into two parts, but also into any number of parts:

javascriptlet str = 'aaa bbb ccc ddd';
let res = str.replace(/a+|b+|c+/g, '!');

As a result, the following will be written to the variable:

javascript'! ! ! ddd'

Example

If the vertical bar is inside parentheses, then 'OR' only works inside those parentheses.

For example, let's find strings with the following pattern: starts with either 'a' or 'b' one or more times, followed by two letters 'x':

javascriptlet str = 'axx bxx bbxx exx';
let res = str.replace(/(a|b+)xx/g, '!');

As a result, the following will be written to the variable:

javascript'! ! ! exx'

Practical tasks

Задание 1

Given a string:

javascriptlet str = 'aeeea aeea aea axa axxa axxxa';

Write a regex that finds strings according to the pattern: there are letters 'a' at the edges, and between them - either the letter 'e' any number of times or letter 'x' any number of times .

Задание 2

Given a string:

javascriptlet str = 'aeeea aeea aea axa axxa axxxa';

Write a regex that finds strings according to the pattern: there are letters 'a' at the edges, and between them - either the letter 'e' twice or letter 'x' any number of times.