Master JavaScript Regex: String Methods and RegExp Object Explained
This article explains the two main aspects of using regular expressions in JavaScript—string methods such as search, replace, match, and split, and the RegExp object with its properties, constructor, and methods like exec, test, and compile, including practical tips and common pitfalls.
Overall, JavaScript involves regular expressions in two areas: string handling and the RegExp object itself. Below we introduce the specific usage of each.
String methods
Four String methods support regular expressions:
search() – Takes a regular expression and returns the index of the first matching substring, or –1 if none. It converts a non‑regex argument to a RegExp and does not support global searches.
replace() – Performs search‑and‑replace. The first argument is a RegExp, the second is the replacement string or a function. When a function is used, its parameters are the matched substring, captured groups, the index, and the original string.
match() – Takes a RegExp and returns an array containing the match results. It supports global matching; with the
gflag it returns all matches, otherwise it returns an array where index 0 is the full match and subsequent indices are captured groups, plus
indexand
inputproperties.
split() – Splits a string by a RegExp. It accepts an optional second argument that limits the length of the resulting array.
RegExp object
Each RegExp instance has five properties:
source – Read‑only string containing the pattern text.
global – Read‑only boolean indicating whether the
gflag is set.
ignoreCase – Read‑only boolean indicating whether the
iflag is set.
multiline – Read‑only boolean indicating whether the
mflag is set.
lastIndex – Read‑write integer that stores the position at which to start the next match.
The RegExp constructor
RegExp(pattern, flags)accepts a pattern string and optional flags (g, i, m, etc.). Using the constructor allows dynamic creation of regular expressions.
Key RegExp methods:
exec() – Similar to
String.match()but takes a string argument. Returns
nullif no match; otherwise returns an array with the same structure as a non‑global
match(). It updates
lastIndexto enable iterative matching.
test() – Returns
trueif the pattern matches the given string, otherwise
false. It also updates
lastIndexfor global patterns.
compile() – Recompiles the RegExp with a new pattern or flags, improving performance when the same pattern is used repeatedly in loops.
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.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.