JS: Regular Expression Functions

By Xah Lee. Date: . Last updated: .

Here is a overview of regex functions.

Do all occurrences

str.matchAll(regexObj)

Return all occurrences and captures.

str.replaceAll(regexObj, rep)

Return a new string.

Match and find and replace (first occurrence or all)

str.match(regexObj)
  • 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(regexObj, rep)

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

Get index of first occurrence

str.search(regexObj)

Return the index of first char of the first match.

Just tell me matched or no

regexObj.test(str)

Return true/false.

Generic

regexObj.exec(str)

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