Lecture Notes Of Day 26:
Regular Expressions in JavaScript
Objective:
To understand how to use regular
expressions (regex) in JavaScript for pattern matching, string validation,
and string manipulation.
Topics
Covered:
1.Regular
Expression Syntax
2.Using the
RegExp() Constructor
3.Methods
for Working with Regular Expressions:
o
test()
o
exec()
o
match()
o
replace()
1.
Regular Expression Syntax
A regular expression
(regex) is a powerful tool used to find patterns in strings or to validate
string inputs. Regular expressions are often used for searching, extracting,
replacing, or validating data in a string.
Basic Syntax Overview:
- Literals:
Regular characters match themselves. Example: /apple/ matches the string "apple".
- Metacharacters:
Special characters that control the behavior of the regular expression.
- .
(dot) matches any character except newlines.
- ^
matches the beginning of a string.
- $
matches the end of a string.
- []
defines a character class.
- |
denotes alternation (OR).
- ()
is used for grouping.
- +
matches one or more occurrences of the preceding element.
- *
matches zero or more occurrences of the preceding element.
- ?
matches zero or one occurrence of the preceding element.
- {n,m}
matches between n and m occurrences of the preceding element.
Examples:
- /a.b/:
Matches any string where a is followed by any character, then b.
- /^abc/:
Matches strings starting with "abc".
- /abc$/:
Matches strings ending with "abc".
- /[aeiou]/:
Matches any vowel.
2. Using
the RegExp() Constructor
In JavaScript, regular
expressions can be created using two methods:
- Regular
expression literal: /pattern/
- RegExp
constructor: new RegExp(pattern, flags)
Syntax:
var regex1 = /pattern/; // Literal notation
var
regex2 = new RegExp('pattern'); // Constructor notation
Constructor syntax:
Constructor syntax allows for dynamic regex patterns, as the pattern can be stored in a variable.
- Flags:
You can add flags to modify the behavior of the regex:
- g
(global): Matches all occurrences.
- i
(ignore case): Makes the search case-insensitive.
- m
(multiline): Changes the behavior of ^ and $ to match the beginning and
end of lines.
Example:
var
pattern = 'apple';
var regex
= new RegExp(pattern, 'i'); // Case-insensitive match for "apple"
3.
Methods for Working with Regular Expressions
JavaScript provides several
methods to work with regular expressions. Some of the most commonly used
methods are:
a. test()
Method
The test() method checks if a
regular expression matches a given string. It returns true if a match is found,
and false if no match is found.
Syntax:
regex.test(string);
Example:
var regex = /hello/;
console.log(regex.test('Hello
world')); // false (case-sensitive)
console.log(regex.test('hello
world')); // true
b. exec()
Method
The exec() method executes a
search for a match in a string. It returns an array of matched results or null
if no match is found.
Syntax:
regex.exec(string);
Example:
var regex = /([a-z]+) ([a-z]+)/;
var
result = regex.exec('hello world');
console.log(result);
//
Output: ['hello world', 'hello', 'world']
c. match()
Method
The match() method is used on
strings and returns an array of all matches found, or null if no matches are
found. It can be used with regular expressions and is often used when searching
for multiple matches in a string.
Syntax:
string.match(regex);
Example:
var str =
"The quick brown fox jumps over the lazy dog.";
var regex
= /\b\w{4}\b/g; // matches all 4-letter words
console.log(str.match(regex));
// Output: ['quick', 'over', 'lazy']
d. replace()
Method
The replace() method searches for
a pattern and replaces it with a specified string or function. If the regular
expression contains the g flag (global), it replaces all occurrences.
Syntax:
string.replace(regex, replacement);
Example:
var str = "The quick brown fox";
var regex
= /fox/;
var
result = str.replace(regex, 'cat');
console.log(result);
// Output: "The quick brown cat"
You can also use a function
as the second argument to modify the replaced string dynamically.
Example with function:
var str =
"The quick brown fox";
var regex
= /(\w+)/g;
var
result = str.replace(regex, function(match, p1) {
return p1.toUpperCase();
});
console.log(result);
// Output: "THE QUICK BROWN FOX"
Practical
Examples of Regular Expressions in JavaScript
1.
Validating Email Address
Regular expressions can be used to validate input fields like email addresses.
var
emailRegex = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$/;
console.log(emailRegex.test("test@example.com"));
// true
console.log(emailRegex.test("invalid-email"));
// false
2.
Matching Dates (MM/DD/YYYY format)
var dateRegex = /^(0[1-9]|1[0-2])\/([0-2][1-9]|3[01])\/\d{4}$/;
console.log(dateRegex.test("12/25/2024"));
// true
console.log(dateRegex.test("2024-12-25"));
// false
3.
Extracting Data (Finding Words with Specific Length)
var str = "The quick brown fox jumps over the lazy dog";
var regex
= /\b\w{5}\b/g; // Match words with exactly 5 letters
console.log(str.match(regex));
// ['quick', 'brown']
4. Common
Use Cases of Regular Expressions
- Form
Validation: Checking if input fields contain valid data
(e.g., email, phone number).
- Search
and Replace: Modifying or formatting strings based on a
pattern.
- Data
Extraction: Extracting specific patterns from a string,
like phone numbers, emails, etc.
- Parsing
Data: Analyzing or extracting information from
logs, documents, or structured text.
Summary
In this lesson, we've learned how
to:
- Understand
and write regular expressions in JavaScript.
- Use
various regular expression methods like test(), exec(), match(), and replace().
- Validate
and manipulate strings using regular expressions.
- Apply
regular expressions for common tasks like form validation, data
extraction, and pattern matching.
Regular expressions are powerful
tools, and mastering them will allow you to handle a wide range of tasks in
JavaScript, especially for string processing.
