|
| 1 | +# Regular expressions |
| 2 | + |
| 3 | +Regular expressions, or 'regex,' are patterns used to match character |
| 4 | +combinations in strings. In JavaScript, regex is a powerful tool for searching, |
| 5 | +replacing, and extracting text. |
| 6 | + |
| 7 | +## Basic syntax |
| 8 | + |
| 9 | +When we are searching some text for a particular pattern, we define the pattern |
| 10 | +in forward slashes like this: |
| 11 | + |
| 12 | +```js |
| 13 | +const pattern = /cat/ |
| 14 | +``` |
| 15 | + |
| 16 | +We can use `test()` to check whether a pattern exists in a string. It returns a |
| 17 | +boolean indicating whether the pattern is found. |
| 18 | + |
| 19 | +```js |
| 20 | +const text = 'The cat sat on the mat.' |
| 21 | +const pattern = /cat/ |
| 22 | +pattern.test(text) // true |
| 23 | +``` |
| 24 | + |
| 25 | +## Dot |
| 26 | + |
| 27 | +The `.` metacharacter matches any single character except a new line. |
| 28 | + |
| 29 | +The pattern below will match `'cat'`, `'mat'`, `'bat'` or anything else which |
| 30 | +looks like 'a single character followed by `'at'`'. |
| 31 | + |
| 32 | +```js |
| 33 | +const pattern = /.at/ |
| 34 | + |
| 35 | +const text1 = 'cat' |
| 36 | +const text2 = 'cap' |
| 37 | + |
| 38 | +pattern.test(text1) // true |
| 39 | +pattern.test(text2) // false |
| 40 | +``` |
| 41 | + |
| 42 | +## Searching for a pattern |
| 43 | + |
| 44 | +To do a **global** search for this pattern through some text, we add the `g` |
| 45 | +modifier and use the `match()` method: |
| 46 | + |
| 47 | +```js |
| 48 | +// add /g for global search |
| 49 | +const pattern = /.at/g |
| 50 | + |
| 51 | +const text = 'The cat sat on the mat.' |
| 52 | +text.match(pattern) // ['cat', 'mat'] |
| 53 | +``` |
| 54 | + |
| 55 | +## Quantifiers |
| 56 | + |
| 57 | +The `+` quantifier matches 1 or more occurences of the preceeding elements: |
| 58 | + |
| 59 | +```js |
| 60 | +const text = 'ac, abc, abbc, abbbc' |
| 61 | +const pattern = /ab+c/g |
| 62 | +text.match(pattern) // ['abc', 'abbc', 'abbbc'] |
| 63 | +``` |
| 64 | + |
| 65 | +Similarly, |
| 66 | + |
| 67 | +- the `*` quantifier matches 0 or more occurences |
| 68 | + |
| 69 | +- the `?` quantifier matches 0 or 1 occurences |
| 70 | + |
| 71 | +## Matching letters and digits |
| 72 | + |
| 73 | +We can use `\d` to match any digit character: |
| 74 | + |
| 75 | +```js |
| 76 | +const text = 'Order 66 was executed at 4:00 PM.' |
| 77 | +const pattern = /\d+/g |
| 78 | +text.match(pattern) // ['66', '4', '00'] |
| 79 | +``` |
| 80 | + |
| 81 | +We can use `\w` to match any word character (letters, digits, underscores): |
| 82 | + |
| 83 | +```js |
| 84 | +const tweet = 'Learning JavaScript is fun! #coding #JavaScript #100DaysOfCode' |
| 85 | +const pattern = /#\w+/g |
| 86 | +const hashtags = tweet.match(pattern) |
| 87 | +console.log(hashtags) // ['#coding', '#JavaScript', '#100DaysOfCode'] |
| 88 | +``` |
0 commit comments