When Should You Use exec vs. match in JavaScript? A Clear Guide

This article explains the fundamental differences between JavaScript's exec and match methods, showing which belongs to RegExp or String, how the global "g" flag affects their behavior, and provides practical code examples to help you choose the right one.

Tencent IMWeb Frontend Team
Tencent IMWeb Frontend Team
Tencent IMWeb Frontend Team
When Should You Use exec vs. match in JavaScript? A Clear Guide

1. Which Object Owns exec and match?

exec is a method of the RegExp class. match is a method of the String class.

Understanding the owning object makes it clear how to use each method.

Example:

/hello/.exec('hello world');
'hello world'.match(/hello/);

2. The Key Difference

In short, it’s about the g flag. exec always matches the first occurrence (the g flag does not affect it) and returns information about captured groups. match returns an array of all matches only when the regular expression includes the g flag.

When the g flag is present, match can return multiple results, while exec still returns only the first match.

Conversely, if the regular expression does not have the g flag, match behaves like exec and returns a single match.

Example code (both functions return ["version2.1","version","2","1"]):

var str = "version2.1";
var re = /([a-z]+)(\d+)\.(\d+)/;
console.log(str.match(re));
console.log(re.exec(str));

In summary, the differences are twofold: they belong to different classes, and their behavior depends on whether the regular expression uses the g flag.

Reference

http://www.cnblogs.com/xiehuiqi220/archive/2008/12/01/1327487.html

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

StringmatchexecRegExp
Tencent IMWeb Frontend Team
Written by

Tencent IMWeb Frontend Team

IMWeb Frontend Community gathering frontend development enthusiasts. Follow us for refined live courses by top experts, cutting‑edge technical posts, and to sharpen your frontend skills.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.