What are Regular Expressions?
Regular expressions are a sequence of characters that define a search pattern. The pattern is used to match character combinations in strings. Regular expressions can be used to search for specific characters, words, or patterns of characters in a string.
For example, the regular expression
/hello/ can be used to search for the word “hello” in a string. The expression
/[a-z]/ can be used to search for any lowercase letter in a string.
RegExp constructor, or by using a regular expression literal.
To create a regular expression using the
RegExp constructor, you can pass a string containing the pattern as an argument.
let pattern = new RegExp("hello");
To create a regular expression using a literal, you can enclose the pattern in forward slashes.
let pattern = /hello/;
Regular Expression Methods
search method searches a string for a specified pattern and returns the index of the first match.
let str = "hello world"; let pattern = /world/; let result = str.search(pattern); // returns 6
replace method replaces a specified pattern with a new string.
let str = "hello world"; let pattern = /world/; let newStr = str.replace(pattern, "universe"); // returns "hello universe"
match method searches a string for a specified pattern and returns an array containing the matches.
let str = "hello world"; let pattern = /o/; let result = str.match(pattern); // returns ["o", "o"]
Regular Expression Syntax
.– Matches any single character except for line terminators
*– Matches zero or more occurrences of the preceding character
+– Matches one or more occurrences of the preceding character
?– Matches zero or one occurrence of the preceding character
\– Escapes special characters
^– Matches the beginning of the string
$– Matches the end of the string
– Matches any character inside the brackets
()– Groups characters together
Regular expressions can also include special characters, such as:
\d– Matches any digit character
\w– Matches any word character (letters, digits, or underscore)
\s– Matches any whitespace character (space, tab, newline, etc.)
\D– Matches any non-digit character
\W– Matches any non-word character
\S– Matches any non-whitespace character