0% found this document useful (0 votes)
20 views5 pages

CHAPTER 5 Regular Expression

Uploaded by

Piush Gogi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views5 pages

CHAPTER 5 Regular Expression

Uploaded by

Piush Gogi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 5

CHAPTER 5: Regular Expression, Rollover and Frames

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:

let regex = /hello/;

let text = "hello world";

console.log(regex.test(text));

This checks if "hello" is in the text and returns true if found.

1. Language of Regular Expressions

Regular expressions use a combination of literal characters and metacharacters to define patterns
that match parts of a string. Here's a breakdown:

- Literal characters: Match exactly the same characters as written.

- Example: `/cat/` matches the exact string "cat" in text.

- Metacharacters: These characters have special meanings in regex:

- `.` (dot): Matches any character except for newline (`\n`).

- Example: `/c.t/` matches "cat", "cut", or "c7t".

- `*` (asterisk): Matches zero or more occurrences of the preceding character.

- Example: `/ca*t/` matches "ct", "cat", "caat", etc.

- `+` (plus): Matches one or more occurrences of the preceding character.

- Example: `/ca+t/` matches "cat", "caat", but not "ct".

- `?` (question mark): Makes the preceding character optional (matches 0 or 1 times).

- Example: `/colou?r/` matches both "color" and "colour".

- `\` (backslash): Escapes special characters so they can be treated as literal characters.

- Example: `/\./` matches a literal dot rather than any character.


2. Finding Non-Matching 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`

This matches any character that is not a vowel.

- Code:

let regex = /[^aeiou]/g; // Find non-vowels

let text = "hello";

console.log(text.match(regex)); // ["h", "l", "l"]

Here, the regex finds all non-vowel characters: "h", "l", and "l".

Example:

- Regex: `/[^a-z]/g`

This matches any character that is not a lowercase letter.

- Code:

let regex = /[^a-z]/g;

let text = "Hello World!";

console.log(text.match(regex)); // ["H", " ", "W", "!", " "]

3. Entering a Range of Characters

In regex, square brackets `[]` define a character class, which matches any one of the characters
inside. You can specify ranges using a hyphen `-`.

Examples:

1. Match lowercase letters: `[a-z]`

- Matches any lowercase letter from "a" to "z".

2. Match uppercase letters: `[A-Z]`

- Matches any uppercase letter from "A" to "Z".


3. Match digits: `[0-9]`

- Matches any digit from 0 to 9.

Regex Example: `/[a-z]/g`

- This matches any lowercase letter in the string.

let regex = /[a-z]/g;

let text = "Hello123";

console.log(text.match(regex)); // ["e", "l", "l", "o"]

4. Matching Digits and Non-Digits

In regex, special shorthand characters can match digits and non-digits:

- `\d`: Matches any digit (0-9).

- `\D`: Matches any non-digit (anything that is not 0-9).

Example:

let regex = /\d/g; // Matches digits

let text = "I have 3 apples and 2 oranges";

console.log(text.match(regex)); // ["3", "2"]

let nonDigitRegex = /\D/g; // Matches non-digits

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"]

5. Matching Punctuation and Symbols

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:

let regex = /[.,!?]/g; // Matches punctuation marks

let text = "Hello, world!";

console.log(text.match(regex)); // [",", "!"]

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_]`.

- `\W`: Matches any non-word character.

Example:

let regex = /\w+/g; // Matches words

let text = "Hello world!";

console.log(text.match(regex)); // ["Hello", "world"]

The `\w+` finds sequences of word characters (letters and numbers), treating them as words.

7. Replacing Text Using Regular Expressions

The `.replace()` method allows you to find and replace text that matches a regex pattern.

Example:

let text = "I have 3 apples";

let regex = /\d+/; // Matches digits

let newText = text.replace(regex, "five");

console.log(newText); // "I have five apples"

Here, the number "3" is replaced with the word "five".

You can also use a function for dynamic replacements:

let text = "I have 3 apples";

let regex = /(\d+)/;

let newText = text.replace(regex, (match) => parseInt(match) + 2);

console.log(newText); // "I have 5 apples"

8. Returning Matched Characters

- `.match()`: Returns an array of all matches found in the string.

- `.exec()`: Returns more detailed information about the match, including its position and input
string.
Example using `.match()`:

let text = "Room 101";

let regex = /\d+/g; // Matches digits

console.log(text.match(regex)); // ["101"]

Example using `.exec()`:

let regex = /\d+/;

let text = "Room 101";

let result = regex.exec(text);

console.log(result); // ["101", index: 5, input: "Room 101", groups: undefined]

9. Regular Expression Object Properties

A `RegExp` object in JavaScript has several properties and methods:

- `.flags`: Displays the flags used in the regex (e.g., `g` for global, `i` for case-insensitive).

- `.source`: Shows the raw text of the regex pattern.

Example:

let regex = /hello/i;

console.log(regex.source); // "hello"

console.log(regex.flags); // "i"

The flags change how the regex behaves:

- `g`: Global search – finds all matches.

- `i`: Case-insensitive – ignores letter casing.

- `m`: Multiline search.

Example using global flag:

let regex = /\d/g; // Global search for digits

let text = "Room 101 has 2 beds";

console.log(text.match(regex)); // ["1", "0", "1", "2"]

The `g` flag ensures that all matches are found, not just the first one.

You might also like