CHAPTER 5 Regular Expression
CHAPTER 5 Regular Expression
Regular Expression:
A regular expression (regex) in JavaScript is a pattern used to match text. You can use it to search,
replace, or validate strings. For example, if you want to find all email addresses in a text, you can
write a regex that looks for patterns like "[email protected]."
In JavaScript, regex is written between two slashes (/pattern/), and you can use it with methods like
.match(), .replace(), and .test().
Example:
console.log(regex.test(text));
Regular expressions use a combination of literal characters and metacharacters to define patterns
that match parts of a string. Here's a breakdown:
- `?` (question mark): Makes the preceding character optional (matches 0 or 1 times).
- `\` (backslash): Escapes special characters so they can be treated as literal characters.
If you want to find characters that do not match a certain set, use the `[^...]` notation. Inside square
brackets `[]`, the caret `^` means "not."
Example:
- Regex: `/[^aeiou]/g`
- Code:
Here, the regex finds all non-vowel characters: "h", "l", and "l".
Example:
- Regex: `/[^a-z]/g`
- Code:
In regex, square brackets `[]` define a character class, which matches any one of the characters
inside. You can specify ranges using a hyphen `-`.
Examples:
Example:
console.log(text.match(nonDigitRegex)); // ["I", " ", "h", "a", "v", "e", " ", " ", "a", "p", "p", "l", "e",
"s", " ", "a", "n", "d", " ", " ", "o", "r", "a", "n", "g", "e", "s"]
Punctuation and symbols are matched literally using their characters, but you can also use:
- `\W`: Matches any non-word character (i.e., punctuation, spaces, and symbols).
Example:
In the example above, the regex matches commas, periods, exclamation points, and question marks.
6. Matching Words
- `\w`: Matches any word character (letters, digits, and underscores). It is equivalent to `[a-zA-Z0-
9_]`.
Example:
The `\w+` finds sequences of word characters (letters and numbers), treating them as words.
The `.replace()` method allows you to find and replace text that matches a regex pattern.
Example:
- `.exec()`: Returns more detailed information about the match, including its position and input
string.
Example using `.match()`:
console.log(text.match(regex)); // ["101"]
- `.flags`: Displays the flags used in the regex (e.g., `g` for global, `i` for case-insensitive).
Example:
console.log(regex.source); // "hello"
console.log(regex.flags); // "i"
The `g` flag ensures that all matches are found, not just the first one.