A regular expression (RegEx) is a pattern used to match character combinations in strings. Regular expressions are used for pattern matching with strings, such as validating inputs, replacing text, or searching for specific patterns in data.
In JavaScript, regular expressions are created using the /pattern/
syntax or by using the RegExp()
constructor:
/abc/
matches the exact string abc
.new RegExp('abc')
does the same as the literal notation.Regular expressions use special characters to define search patterns:
.
(dot): Matches any single character except newline.\d
: Matches any digit (0-9).\w
: Matches any word character (letters, digits, and underscores).\s
: Matches any whitespace character (spaces, tabs, newlines).^
: Matches the beginning of a string.$
: Matches the end of a string.Here are some commonly used regular expression patterns in JavaScript:
/^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$/
/^\d{3}-\d{3}-\d{4}$/
/https?:\/\/[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/
/\d{2}\/\d{2}\/\d{4}/
JavaScript provides several methods for working with regular expressions:
test()
: Tests if a string matches the regular expression. Returns true
or false
.exec()
: Executes a search for a match and returns the result in an array, or null
if no match is found.match()
: Returns an array of all matches in a string.replace()
: Replaces matched substrings with a new string.split()
: Splits a string into an array of substrings based on a regular expression.RegEx can be modified using flags to customize its behavior:
g
(global): Matches all occurrences in the string, not just the first one.i
(ignore case): Makes the match case-insensitive.m
(multiline): Allows matching across multiple lines.Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!