You already know that special characters
inside []
become regular characters.
There are, however, exceptions: if you need
square brackets as regular characters inside
[ ]
, then you need to escape them with
a backslash. For example, in the following code,
the search pattern looks like this: there is
a square bracket between x's:
let str = 'x]x xax x[x x1x';
let res = str.replace(/x[\[\]]x/g, '!');
As a result, the following will be written to the variable:
'! xax ! x1x'
Given a string:
let str = 'x[]z x[[]]z x()z';
Write a regex that matches all words
in the pattern: letter 'x'
,
then square brackets any number of times,
then letter 'z'
.
Given a string:
let str = 'x[]z x{}z x.z x()z x([])z';
Write a regex that matches all words in
the pattern: letter 'x'
, then
any number of any brackets, then letter
'z'
.