A regular expression, commonly known as a “regex” or “regexp”, is a string that describes a search pattern. You can use regular expressions to check if a string contains a certain pattern, extract information from a string, or replace parts of a string with new text.
Learn the basic syntax of regular expressions and how to use them in JavaScript.
Basic regular expression syntax
To create regular expressions in JavaScript, you can use regular expression literals and Regular expression constructor.
A regular expression literal consists of a pattern enclosed in slashes followed by optional flags.
for example:
const regexExpression_1 = /pattern/
const regexExpression_2 = /pattern/flag
Flags are optional parameters that can be added to a regular expression to change its behavior. for example:
const regexFlag = /the/g;
of g flag indicates that the expression should match all occurrences, not just the first.
You can also create regular expressions using Regular expression constructor. for example:
const regexExpression = new RegExp("Pattern", "g");
of Regular expression The constructor takes two parameters: a pattern (string or regular expression literal) and flags.
There are two fairly common flags for use in JavaScript regular expressions.
- gThe : global flag causes the regular expression to match all occurrences of the pattern in the given string instead of just a single occurrence.
- IThe : case-insensitive flag causes the regular expression to ignore the case of the pattern and match the case of the given string.
Flags can be used together in any order in a single expression. for example:
const regexExpression = new RegExp("Pattern", "gi");
This expression matches all occurrences of “pattern” regardless of case.
Certain characters, called metacharacters, have special meaning in regular expressions. You can use them to match specific types of characters or patterns.
Here are some of the most commonly used metacharacters and their meanings.
- The wildcard character (.): This character matches any single character except newline. A useful tool for matching unknown characters and patterns.
- Kleene Star (*): This character matches zero or more occurrences of the preceding character or group. This allows the preceding character or group to appear any number of times within the string, including zero.
- Option character (?): This character matches zero or one occurrence of the preceding character or group.
- Start of line anchor (^): This character matches only the beginning of a line or string.
- End of line anchor ($): This character matches the end of a line or string.
- charset/class ([]): charset matches any character of the charset in the string.Use square brackets to define them [] You can also specify a set of fixed characters, special characters, or specific groups of characters.
- Alternate character (| |): This character matches the preceding or following character or group. Works like the OR JavaScript operator.
- grouping character (()): The grouping character allows you to group characters or subexpressions, apply operators to them as a unit, and control the order of operations.
Testing strings against regular expressions in JavaScript
In JavaScript, you can test strings against regular expressions using several methods.
test method
of . test() The method returns a Boolean value indicating whether the regular expression matches the string. This method takes as an argument a string to perform the search on. This is especially useful for simple checks.
for example:
let regex = /.com$/;
let str = "example.com";
console.log(regex.test(str));
This regular expression matches strings that end with “.com”.
exec-method
of .exec() The method returns an array containing the matched text and captured groups. null if no match is found. This method takes as an argument a string to perform the search on. Useful for more complex regular expressions.
for example:
let regex = /^\\(?([0-9]{3})\\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/;
let str = "123-456-7890";
let result = regex.exec(str);if (result !== null) {
console.log(`${result[0]} is a valid phone number`);
} else {
console.log("Invalid phone number");
}
The regex above uses the optional “(“, 3 digits, and an optional “)“. Then look for options”–“,”.“, or a space followed by three digits, optionally followed by “–“,”.“, or a space followed by four digits at the end of the string.
This regular expression matches phone numbers in the format “(xxx) xxx-xxxx”, “xxx-xxx-xxxx”, “xxx.xxx.xxxx”, or “xxx xxx xxxx”.
If a match is found, .exec() Returns an array containing the matched text and captured groups (defined by parentheses). Each group is included as an additional element in the returned array. This gives you access to specific parts of the matched text, useful for extracting information from strings.
Replacement method
of . exchange() The method searches for regular expression and string matches and replaces the matched text with the specified replacement text. This is a string object method and takes a regular expression and a replacement string as arguments.
for example:
let string = "The quick brown fox jumps over the lazy dog.";
let expression = /The/gi;
let newString = string.replace(expression, "a");
console.log(newString);
In this example, exchange() method above string pass variables, regular expressions, ExpressionThe regular expression matches all “The” in the string regardless of case. A call to the replace method tells it to replace each occurrence with the string “a”.
Performance considerations when using regular expressions
Regular expressions are useful for matching and manipulating strings, but they can be costly in terms of performance. Keeping patterns as specific and simple as possible is essential to maintaining performance.