JS: Regular Expression Functions

By Xah Lee. Date: . Last updated: .

Here is a overview of regex functions.

Do all occurrences

str.matchAll(regex_obj)

Return all occurrences and captures.

str.replaceAll(regex_obj, rep)

Return a new string.

Get index of first occurrence

str.search(regex_obj)

Return the index of first char of the match.

First occurrence (if no g flag)

str.match(regex_obj)
  • If regex has g flag → return all occurrences
  • If regex has no g flag → return captured groups.
  • If regex has no g flag nor capture → return first match.
str.replace(regex_obj, rep)

Replace first occurrence (or all). Return a new string.

Just tell me matched or no

regex_obj.test(str)

Return true/false.

Get captured groups, or

regex_obj.exec(str)

Return captured groups.