JavaScript Regular Expressions: Literal vs Constructor
I’ve never systematically summarized the differences between literals and constructors when declaring regular expressions, so I’m taking some time to do that now.
Differences
- In literals, special characters are parsed directly, while in constructors you need to add backslashes for escaping. For example, \d is treated as the string \d, but
- The forward slashes around literals are just delimiters to indicate it’s a regular expression. If you write them in a constructor, they mean matching actual slashes
- Literal expressions have better readability than constructors
Examples
The following regular expression matches are equivalent:
const value = 'rt:60C1C036-42FA-4073-B10B-1969BD2358FB@00000000077';
console.log(new RegExp('rt:([^@]+)@(\\d+)').exec(value));
console.log(/rt:([^@]+)@(\d+)/.exec(value));
How to Choose
If the regular expression pattern is fixed, prefer using literals. But if the pattern is a variable that needs to be determined from context, then you should use the constructor.
Extension
Literals vs Variables
Literals are different from variables. For example, in a=1
, a is a variable, but we can also say that 1 is a literal because we can directly see what the value is from its appearance. So literals refer to values, while variables refer to parameters - one on the left side, one on the right side.
Final Thoughts
Text processing inevitably involves regular expressions, so it’s important to pay attention and summarize these concepts.