JavaScript Regular Expressions: Literal vs Constructor

This article explains the differences between JavaScript regular expression literals and constructors, including their advantages, implementation details, and related resources. These concepts help improve efficiency when working with regular expressions in JavaScript.

Nov 28, 2020 · 1 min read · 210 Words · -Views -Comments · Programming
JavaScript 🇨🇳 阅读中文版
Read with AI

Choose an AI assistant

ChatGPT Open in a new tab with the article link and prompt
Claude Copy the prompt, then open Claude

Open Claude
Trouble reading the article?

If the prompt is missing, copy the full prompt below into your AI assistant. If the AI cannot read the article, paste the visible passage you want to discuss and add your question.

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.

Authors
Developer, digital product enthusiast, tinkerer, sharer, open source lover