Regular expressions (regex) in JavaScript are patterns used to match character combinations in strings. They are powerful tools for searching, matching, and replacing text.
Creating Regular Expressions
There are two ways to create a regular expression in JavaScript:
- Using Literal Syntax:
let regex = /pattern/;
- Using Constructor:
let regex = new RegExp("pattern");
Basic Syntax
/pattern/flags
: The pattern is the text to search for, and the flags modify the search.
Common Flags:
g
: Global search (find all matches).i
: Case-insensitive search.m
: Multi-line search.
Example:
let regex = /hello/i; // Case-insensitive match for "hello"
Common Regex Patterns
- Literal Characters: Match exact characters.
/cat/
matches “cat”.
- Meta Characters: Special characters with specific meanings.
.
: Matches any single character except newline.^
: Matches the beginning of a string.$
: Matches the end of a string.*
: Matches 0 or more of the preceding element.+
: Matches 1 or more of the preceding element.?
: Matches 0 or 1 of the preceding element.
Example:
let regex = /ca./; // Matches "cat", "car", "can", etc.
Character Classes
[abc]
: Matches any of the characters in the brackets.[^abc]
: Matches any character not in the brackets.[0-9]
: Matches any digit.[a-z]
: Matches any lowercase letter.[A-Z]
: Matches any uppercase letter.
Example:
let regex = /[0-9]/; // Matches any digit
Predefined Character Classes
\d
: Matches any digit (equivalent to[0-9]
).\D
: Matches any non-digit character.\w
: Matches any alphanumeric character (equivalent to[A-Za-z0-9_]
).\W
: Matches any non-word character.\s
: Matches any whitespace character.\S
: Matches any non-whitespace character.
Example:
let regex = /\d/; // Matches any digit
Quantifiers
Quantifiers specify how many times a character or group should be matched.
{n}
: Matches exactly n occurrences.{n,}
: Matches n or more occurrences.{n,m}
: Matches between n and m occurrences.
Example:
let regex = /a{2,4}/; // Matches "aa", "aaa", or "aaaa"
Regex Methods
-
test()
: Tests for a match in a string. Returnstrue
orfalse
.let regex = /cat/; console.log(regex.test("The cat is here.")); // true
exec()
: Executes a search for a match in a string. Returns an array of matched results ornull
.
let regex = /cat/; console.log(regex.exec("The cat is here.")); // ["cat"]
- String Methods with Regex:
match()
: Returns an array of matches ornull
.replace()
: Replaces matched substring with a new substring.search()
: Searches for a match and returns the index or-1
.split()
: Splits a string into an array using the regex.
Example:
let str = "The cat is here."; let regex = /cat/; console.log(str.match(regex)); // ["cat"]
Conclusion
Regular expressions are a powerful tool in JavaScript for text processing tasks like validation, searching, and replacing. By mastering regex patterns and methods., you can handle complex string operations efficiently.