Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit f21cb0a

Browse files
committed
WIP
1 parent ef370b6 commit f21cb0a

File tree

71 files changed

+698
-718
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

71 files changed

+698
-718
lines changed

‎9-regular-expressions/01-regexp-introduction/article.md‎

Lines changed: 105 additions & 53 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
Regular expressions is a powerful way to search and replace in text.
44

5-
In JavaScript, they are available as `RegExp` object, and also integrated in methods of strings.
5+
In JavaScript, they are available as [RegExp](mdn:js/RegExp) object, and also integrated in methods of strings.
66

77
## Regular Expressions
88

@@ -23,35 +23,43 @@ regexp = /pattern/; // no flags
2323
regexp = /pattern/gmi; // with flags g,m and i (to be covered soon)
2424
```
2525

26-
Slashes `"/"` tell JavaScript that we are creating a regular expression. They play the same role as quotes for strings.
26+
Slashes `pattern:/.../` tell JavaScript that we are creating a regular expression. They play the same role as quotes for strings.
2727

28-
## Usage
28+
In both cases `regexp` becomes an object of the built-in `RegExp` class.
2929

30-
To search inside a string, we can use method [search](mdn:js/String/search).
30+
The main difference between these two syntaxes is that slashes `pattern:/.../` do not allow to insert expressions (like strings with `${...}`). They are fully static.
3131

32-
Here's an example:
32+
Slashes are used when we know the regular expression at the code writing time -- and that's the most common situation. While `new RegExp` is used when we need to create a regexp "on the fly", from a dynamically generated string, for instance:
3333

34-
```js run
35-
let str = "I love JavaScript!"; // will search here
34+
```js
35+
let tag = prompt("What tag do you want to find?", "h2");
3636

37-
let regexp = /love/;
38-
alert( str.search(regexp) ); // 2
37+
let regexp = new RegExp(`<${tag}>`); // same as /<h2>/ if answered "h2" in the prompt above
3938
```
4039

41-
The `str.search` method looks for the pattern `pattern:/love/` and returns the position inside the string. As we might guess, `pattern:/love/` is the simplest possible pattern. What it does is a simple substring search.
40+
## Flags
4241

43-
The code above is the same as:
42+
Regular expressions may have flags that affect the search.
4443

45-
```js run
46-
let str = "I love JavaScript!"; // will search here
44+
There are only 6 of them in JavaScript:
4745

48-
let substr = 'love';
49-
alert( str.search(substr) ); // 2
50-
```
46+
`pattern:i`
47+
: With this flag the search is case-insensitive: no difference between `A` and `a` (see the example below).
5148

52-
So searching for `pattern:/love/` is the same as searching for `"love"`.
49+
`pattern:g`
50+
: With this flag the search looks for all matches, without it -- only the first one.
5351

54-
But that's only for now. Soon we'll create more complex regular expressions with much more searching power.
52+
`pattern:m`
53+
: Multiline mode (covered in the chapter <info:regexp-multiline-mode>).
54+
55+
`pattern:s`
56+
: Enables "dotall" mode, that allows a dot `pattern:.` to match newline character `\n` (covered in the chapter <info:regexp-character-classes>).
57+
58+
`pattern:u`
59+
: Enables full unicode support. The flag enables correct processing of surrogate pairs. More about that in the chapter <info:regexp-unicode>.
60+
61+
`pattern:y`
62+
: "Sticky" mode: searching at the exact position in the text (covered in the chapter <info:regexp-sticky>)
5563

5664
```smart header="Colors"
5765
From here on the color scheme is:
@@ -61,65 +69,109 @@ From here on the color scheme is:
6169
- result -- `match:green`
6270
```
6371

72+
## Searching: str.match
6473

65-
````smart header="When to use `new RegExp`?"
66-
Normally we use the short syntax `/.../`. But it does not support variable insertions `${...}`.
74+
As it was said previously, regular expressions are integrated with string methods.
6775

68-
On the other hand, `new RegExp` allows to construct a pattern dynamically from a string, so it's more flexible.
76+
The method `str.match(regexp)` finds all matches of `regexp` in the string`str`.
6977

70-
Here's an example of a dynamically generated regexp:
78+
It has 3 working modes:
7179

72-
```js run
73-
let tag =prompt("Which tag you want to search?", "h2");
74-
let regexp = newRegExp(`<${tag}>`);
80+
1. If the regular expression has flag `pattern:g`, it returns an array of all matches:
81+
```js run
82+
let str = "We will, we will rock you";
7583

76-
// finds <h2> by default
77-
alert( "<h1> <h2> <h3>".search(regexp));
78-
```
79-
````
84+
alert( str.match(/we/gi) ); // We,we (an array of 2 matches)
85+
```
86+
Please note that both `match:We` and `match:we` are found, because flag `pattern:i` makes the regular expression case-insensitive.
8087

88+
2. If there's no such flag it returns only the first match in the form of an array, with the full match at index `0` and some additional details in properties:
89+
```js run
90+
let str = "We will, we will rock you";
8191
82-
## Flags
92+
let result = str.match(/we/i); // without flag g
8393
84-
Regular expressions may have flags that affect the search.
94+
alert( result[0] ); // We (1st match)
95+
alert( result.length ); // 1
8596
86-
There are only 6 of them in JavaScript:
97+
// Details:
98+
alert( result.index ); // 0 (position of the match)
99+
alert( result.input ); // We will, we will rock you (source string)
100+
```
101+
The array may have other indexes, besides `0` if a part of the regular expression is enclosed in parentheses. We'll cover that in the chapter <info:regexp-groups>.
87102

88-
`i`
89-
: With this flag the search is case-insensitive: no difference between `A` and `a` (see the example below).
103+
3. And, finally, if there are no matches, `null` is returned (doesn't matter if there's flag `pattern:g` or not).
90104

91-
`g`
92-
: With this flag the search looks for all matches, without it -- only the first one (we'll see uses in the next chapter).
105+
That's a very important nuance. If there are no matches, we get not an empty array, but `null`. Forgetting about that may lead to errors, e.g.:
93106
94-
`m`
95-
: Multiline mode (covered in the chapter <info:regexp-multiline-mode>).
107+
```js run
108+
let matches = "JavaScript".match(/HTML/); // = null
96109
97-
`s`
98-
: "Dotall" mode, allows `.` to match newlines (covered in the chapter <info:regexp-character-classes>).
110+
if (!matches.length) { // Error: Cannot read property 'length' of null
111+
alert("Error in the line above");
112+
}
113+
```
99114
100-
`u`
101-
: Enables full unicode support. The flag enables correct processing of surrogate pairs. More about that in the chapter <info:regexp-unicode>.
115+
If we'd like the result to be always an array, we can write it this way:
116+
117+
```js run
118+
let matches = "JavaScript".match(/HTML/)*!* || []*/!*;
102119
103-
`y`
104-
: Sticky mode (covered in the chapter <info:regexp-sticky>)
120+
if (!matches.length) {
121+
alert("No matches"); // now it works
122+
}
123+
```
105124

106-
We'll cover all these flags further in the tutorial.
125+
## Replacing:str.replace
107126

108-
For now, the simplest flag is `i`, here's an example:
127+
The method `str.replace(regexp, replacement)` replaces matches with `regexp` in string `str` with `replacement` (all matches, if there's flag `pattern:g`, otherwise only the first one).
128+
129+
For instance:
109130
110131
```js run
111-
let str = "I love JavaScript!";
132+
// no flag g
133+
alert( "We will, we will".replace(/we/i, "I") ); // I will, we will
134+
135+
// with flag g
136+
alert( "We will, we will".replace(/we/ig, "I") ); // I will, I will
137+
```
138+
139+
The second argument is the `replacement` string. We can use special character combinations in it to insert fragments of the match:
112140
113-
alert( str.search(/LOVE/i) ); // 2 (found lowercased)
141+
| Symbols | Action in the replacement string |
142+
|--------|--------|
143+
|`$&`|inserts the whole match|
144+
|<code>$&#096;</code>|inserts a part of the string before the match|
145+
|`$'`|inserts a part of the string after the match|
146+
|`$n`|if `n` is a 1-2 digit number, then it inserts the contents of n-th parentheses, more about it in the chapter <info:regexp-groups>|
147+
|`$<name>`|inserts the contents of the parentheses with the given `name`, more about it in the chapter <info:regexp-groups>|
148+
|`$$`|inserts character `$` |
149+
150+
An example with `pattern:$&`:
151+
152+
```js run
153+
alert( "I love HTML".replace(/HTML/, "$& and JavaScript") ); // I love HTML and JavaScript
154+
```
155+
156+
## Testing: regexp.test
157+
158+
The method `regexp.test(str)` looks for at least one match, if found, returns `true`, otherwise `false`.
159+
160+
```js run
161+
let str = "I love JavaScript";
162+
let reg = /LOVE/i;
114163

115-
alert( str.search(/LOVE/) ); // -1 (nothing found without 'i' flag)
164+
alert( reg.test(str) ); // true
116165
```
117166
118-
So the `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.
167+
Further in this chapter we'll study more regular expressions, come across many other examples and also meet other methods.
119168
169+
Full information about the methods is given in the article <info:regexp-methods>.
120170
121171
## Summary
122172
123-
- A regular expression consists of a pattern and optional flags: `g`, `i`, `m`, `u`, `s`, `y`.
124-
- Without flags and special symbols that we'll study later, the search by a regexp is the same as a substring search.
125-
- The method `str.search(regexp)` returns the index where the match is found or `-1` if there's no match. In the next chapter we'll see other methods.
173+
- A regular expression consists of a pattern and optional flags: `pattern:g`, `pattern:i`, `pattern:m`, `pattern:u`, `pattern:s`, `pattern:y`.
174+
- Without flags and special symbols that we'll study later, the search by a regexp is the same as a substring search.
175+
- The method `str.match(regexp)` looks for matches: all of them if there's `pattern:g` flag, otherwise only the first one.
176+
- The method `str.replace(regexp, replacement)` replaces matches with `regexp` by `replacement`: all of them if there's `pattern:g` flag, otherwise only the first one.
177+
- The method `regexp.test(str)` returns `true` if there's at least one match, otherwise `false`.

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /