JS: Regex Find/Replace

By Xah Lee. Date: . Last updated: .

Regex means Regular Expression. It is used to check if a string contains certain pattern, or extract the pattern, or replace it with other string. For example, extract email addresses in a text file.

For basic tutorial, see JS: RegExp Tutorial

There are 2 ways to use RegExp in JavaScript:

Following is a summary of the different methods.

String.prototype.search

str.search(/pattern/)

Use this if you want to know position (index) of a pattern.

[see JS: String.prototype.search]

String.prototype.match

This method is used for one of two purposes.

[see JS: String.prototype.match]

String.prototype.replace

str.replace(regex,replace_str_or_func)

Use this if you want to do string replacement.

[see JS: String.prototype.replace]

RegExp.prototype.test

regex.test(string)

Return true or false.

Use this if you just want to know if a pattern matches.

[JS: RegExp.prototype.test]

RegExp.prototype.exec

regex.exec(string)

Return a array of captured groups.

[JS: RegExp.prototype.exec]

JS RegExp

  1. RegExp Tutorial
  2. RegExp Syntax
  3. Regex Find/Replace

JS String

  1. String Overview
  2. Template String
  3. Char, Code Unit, Codepoint
  4. String Escape Sequence
  5. Unicode Escape Sequence
Liket it? I spend 2 years writing this tutorial. Help me spread it. Tell your friends. Or, Put $5 at patreon.

Or, Buy JavaScript in Depth

If you have a question, put $5 at patreon and message me.

Web Dev Tutorials

  1. HTML
  2. Visual CSS
  3. JS in Depth
  4. JS Object Ref
  5. DOM Scripting
  6. SVG
  7. Blog