Regular expressions is a powerful way of searching and replacing inside a string.
RegExp class and integrated with strings.
A regular expression (also “regexp”, or just “reg”) consists of a pattern and optional flags.
There are two syntaxes to create a regular expression object.
The long syntax:
regexp = new RegExp("pattern", "flags");
…And the short one, using slashes
regexp = /pattern/; // no flags regexp = /pattern/gmi; // with flags g,m and i (to be covered soon)
To search inside a string, we can use method search.
Here’s an example:
str.search method looks for the pattern
/love/ and returns the position inside the string. As we might guess,
/love/ is the simplest possible pattern. What it does is a simple substring search.
The code above is the same as:
So searching for
/love/ is the same as searching for
But that’s only for now. Soon we’ll create more complex regular expressions with much more searching power.
From here on the color scheme is:
- regexp –
- string (where we search) –
- result –
Normally we use the short syntax
/.../. But it does not allow any variable insertions, so we must know the exact regexp at the time of writing the code.
On the other hand,
new RegExp allows to construct a pattern dynamically from a string.
So we can figure out what we need to search and create
new RegExp from it:
Regular expressions may have flags that affect the search.
- With this flag the search is case-insensitive: no difference between
a(see the example below).
- With this flag the search looks for all matches, without it – only the first one (we’ll see uses in the next chapter).
- Multiline mode (covered in the chapter Article "regexp-multiline" not found).
- “Dotall” mode, allows
.to match newlines (covered in the chapter Character classes).
- Enables full unicode support. The flag enables correct processing of surrogate pairs. More about that in the chapter Unicode: flag "u".
- Sticky mode (covered in the chapter Sticky flag "y", searching at position)
We’ll cover all these flags further in the tutorial.
For now, the simplest flag is
i, here’s an example:
i flag already makes regular expressions more powerful than a simple substring search. But there’s so much more. We’ll cover other flags and features in the next chapters.
- A regular expression consists of a pattern and optional flags:
- Without flags and special symbols that we’ll study later, the search by a regexp is the same as a substring search.
- The method
str.search(regexp)returns the index where the match is found or
-1if there’s no match. In the next chapter we’ll see other methods.