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.

Match and find and replace (first occurrence or all)

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.

Get index of first occurrence

str.search(regex_obj)

Return the index of first char of the first match.

Just tell me matched or no

regex_obj.test(str)

Return true/false.

Generic

regex_obj.exec(str)

This is a general purpose function, all other regex functions can be implemented by this. Except the replace ones.