Skip to content

Commit 7fceb96

Browse files
authored
Update 40-RegExp.md
1 parent 7d5ec63 commit 7fceb96

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

notes/English/40-RegExp.md

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
## Regular Expression
2+
3+
A regular expression, also known as regex or regexp, is a pattern that is used to match and manipulate text. It is a powerful tool for string manipulation, searching, and validation.
4+
5+
In JavaScript, you can create a regular expression using the RegExp object, or by using a regular expression literal. Here are some examples:
6+
7+
8+
```javascript
9+
// Using the RegExp constructor
10+
const regex1 = new RegExp("hello");
11+
console.log(regex1.test("hello world")); // output: true
12+
13+
// Using a regular expression literal
14+
const regex2 = /world/;
15+
console.log(regex2.test("hello world")); // output: true
16+
```
17+
18+
In the above examples, the regular expressions are used to test if a string contains a specific substring. The test() method returns true if the substring is found, and false otherwise.
19+
20+
Regular expressions can also contain special characters and syntax to match more complex patterns. Here are some examples:
21+
22+
```javascript
23+
// Matching a sequence of digits
24+
const regex3 = /\d+/;
25+
console.log(regex3.test("12345")); // output: true
26+
27+
// Matching a valid email address
28+
const regex4 = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
29+
console.log(regex4.test("[email protected]")); // output: true
30+
31+
// Replacing all occurrences of a substring
32+
const regex5 = /apple/g;
33+
const text = "I like apples, but not pineapples.";
34+
console.log(text.replace(regex5, "orange")); // output: I like oranges, but not pineoranges.
35+
```
36+
37+
In the first example, the \d+ pattern matches one or more digits in a row. In the second example, the regular expression matches a valid email address according to a specific pattern. In the third example, the replace() method is used to replace all occurrences of a substring in a string.
38+
39+
Regular expressions are a powerful tool for string manipulation and validation in JavaScript. They can be used for a wide range of tasks, from simple substring matching to complex pattern matching and replacement.

0 commit comments

Comments
 (0)