JavaScript > Regular Expressions > RegExp Basics > Creating regular expressions
Creating Regular Expressions in JavaScript
Learn how to create regular expressions in JavaScript using both literal and constructor methods, understanding their differences and use cases for pattern matching.
Literal Notation
The literal notation uses forward slashes /
to enclose the regular expression pattern. It's ideal when the pattern is known at the script's evaluation time because the regex is compiled once when the script loads. This approach is generally more performant for static patterns.
// Creating a regex using literal notation
const regexLiteral = /abc/;
// Testing the regex
const text = 'abcdefg';
const result = regexLiteral.test(text); // Returns true
console.log(result);
Constructor Notation
The RegExp constructor takes the regular expression pattern as a string argument. It's useful when the pattern is dynamic or needs to be constructed at runtime, for example, when the pattern is derived from user input or a variable. The constructor notation compiles the regular expression at runtime each time it's called.
// Creating a regex using the RegExp constructor
const regexConstructor = new RegExp('abc');
// Testing the regex
const text = 'abcdefg';
const result = regexConstructor.test(text); // Returns true
console.log(result);
Flags with Literal Notation
Flags can be added after the closing forward slash in the literal notation. Common flags include i
for case-insensitive matching and g
for global matching (finding all matches instead of stopping after the first). The m
flag is used for multiline matching.
// Creating a regex with the 'i' flag (case-insensitive)
const regexLiteralCaseInsensitive = /abc/i;
// Testing the regex
const text1 = 'Abcdefg';
const result1 = regexLiteralCaseInsensitive.test(text1); // Returns true
console.log(result1);
// Creating a regex with the 'g' flag (global search)
const regexLiteralGlobal = /abc/g;
const text2 = 'abc abc abc';
const result2 = text2.match(regexLiteralGlobal); // Returns ['abc', 'abc', 'abc']
console.log(result2);
Flags with Constructor Notation
With the RegExp constructor, flags are passed as the second argument, a string containing one or more flag characters.
// Creating a regex with flags using the RegExp constructor
const regexConstructorCaseInsensitive = new RegExp('abc', 'i');
// Testing the regex
const text1 = 'Abcdefg';
const result1 = regexConstructorCaseInsensitive.test(text1); // Returns true
console.log(result1);
// Creating a regex with the 'g' flag (global search)
const regexConstructorGlobal = new RegExp('abc', 'g');
const text2 = 'abc abc abc';
const result2 = text2.match(regexConstructorGlobal); // Returns ['abc', 'abc', 'abc']
console.log(result2);
Escaping Special Characters
When using the RegExp constructor, you need to escape special characters (like \
, d
, +
, *
, ?
, .
, ^
, $
, |
, (
, )
, [
, ]
, {
, }
) with an additional backslash. In the literal notation, the level of escaping needed is often less (but still necessary in some cases). For instance, to match a literal backslash, you would use \\
in the constructor but often only \
in the literal.
// Using the RegExp constructor with special characters that need escaping
const regexEscaped = new RegExp('\\d+'); // Matches one or more digits
const text = '12345';
const result = regexEscaped.test(text); // Returns true
console.log(result);
// Using literal notation:
const regexLiteralEscaped = /\d+/;
const resultLiteral = regexLiteralEscaped.test(text);
console.log(resultLiteral);
Concepts Behind the Snippet
Regular expressions are patterns used to match character combinations in strings. JavaScript provides two ways to create RegExp objects: using a literal notation and using the RegExp constructor. Understanding the difference is crucial for writing efficient and maintainable code.
Real-Life Use Case
Imagine validating a username. You might want to ensure it only contains alphanumeric characters and underscores. Using the RegExp constructor, you could dynamically create a regex based on the length requirements defined in a configuration file or from user input.
//Example with constructor
const minLength = 5;
const maxLength = 15;
const pattern = `^[a-zA-Z0-9_]{${minLength},${maxLength}}$`;
const usernameRegex = new RegExp(pattern);
const username = 'valid_username';
console.log(usernameRegex.test(username)); // Output: true
Best Practices
Interview Tip
Be prepared to explain the difference between literal and constructor notation, including when each is appropriate. Also, be ready to discuss common regex flags and their impact on matching behavior.
When to Use Them
Memory Footprint
Literal regexes are compiled once at script load, potentially reducing memory overhead compared to repeated construction using the RegExp constructor. However, the difference is generally negligible for simple regexes.
Alternatives
While regular expressions are powerful, sometimes simpler string methods like includes()
, startsWith()
, and endsWith()
can be more efficient for basic string matching tasks. Consider these alternatives before resorting to regexes for every string manipulation task.
Pros
Cons
FAQ
-
When should I use the RegExp constructor over the literal notation?
Use the RegExp constructor when your regex pattern is dynamic or needs to be built at runtime, for instance, when you're incorporating user input or configuration values into the pattern. -
How do I include variables in a regular expression pattern?
When using the RegExp constructor, you can use template literals to embed variables directly into the regex pattern string. For example:const searchTerm = 'example'; const regex = new RegExp(`.*${searchTerm}.*`);
. Note the use of backticks for the template literal. -
Are regular expressions case-sensitive by default?
Yes, regular expressions are case-sensitive by default. To perform a case-insensitive match, use thei
flag (e.g.,/pattern/i
ornew RegExp('pattern', 'i')
).