JS: RegExp Syntax

By Xah Lee. Date: . Last updated: .

This page covers regex pattern syntax.

(For basic examples of how to use regex, see JS: RegExp Tutorial)

Regex pattern has 2 parts:

RegExp Flags

Regex flags are specified in 2 ways:

[see JS: RegExp Constructor]

Regex flag changes the meaning of the pattern, or the behavior of the regex function.

[see JS: Regex Find/Replace]

Regex Flags
flagmeaning
g“global”. Find all matches. Don't stop after first found.
iignore case
m“multiline”; make the RegExp syntax ^ and $ match any newline beginning/end. (not just the beginning/end of whole string)
u(ES2015) “unicode”. Treat string as sequence of unicode characters. If your string contains a character whose codepoint is ≥ 2^16, you shoud set this flag. [see JS: Character, Code Unit, Codepoint]
y(ES2015) “sticky”; match starts at the index RegExp.prototype.lastIndex, except that the pattern ^ will always be beginning of string or line.

Example of using regex flag.

// check if the string contains t
console.log( "WATER".search( /t/ ) === -1);

// ignore case
console.log( "WATER".search( /t/i ) === 2 );

// return value is the start position of match, or -1 if not found

Special Escapes for Literal Characters

RegExp Special Escapes
\0the NUL character (ASCII 0)
\thorizontal tab (common tab char)
\nline feed (unix newline char)
\vvertical tab (rarely used)
\fform feed (often used in emacs as code section break)
\rcarriage return (used in Mac OS Classic as newline)
\xxxa ASCII character of hex code xx. For example, /\x61/ matches the letter “a” (ASCII code 97, hex 61)
\uxxxxa Unicode character with hex code xxxx. It must be 4 digits. Add 0 in front if not. For example, /\u03b1/ matches “α” (codepoint 945, hex 3b1)
\cXa ASCII control character. For example, /\cJ/ matches the unix newline \n.
[\b]a backspace.

[see ASCII Characters ␀ ␣ ¶]

// example of RegExp matching unicode by hex codepoint

console.log( "alpha α".search(/\u03b1/)); // 6

console.log( "alpha α".search(/α/)); // 6
// literal Unicode char is ok too

Character Sets, Character Classes

RegExp Character Classes
syntaxmeaning
[…]any character between the brackets.
[^…]any char that's not one of the character in the brackets.
.any char, except newline characters: {\n, \r, \u2028, \u2029}.
\wany letter (upper or lower) or digit or low line _.
\Wany character that is not \w.
\dany ASCII digit 0 to 9.
\Dany character that's not \d.
\sany Unicode whitespace character.
\Sany character that is not \s.
// check if string contain digit

console.log (
 "xyz 123".search( /\d/ )
); // 4

Boundaries

RegExp Character Classes
syntaxmeaning
^beginning of string. If flag g is set, also match beginning of lines.
$end of string. If flag g is set, also match end of line.
\bword boundary. For literal backspace, use [\b]
\BNot word boundary.
// example of regex with boundary check

console.log ( "something".search( /thing/ ) ); // 4

// check for “thing” if it's a word by itself
console.log ( "something".search( /\bthing\b/ ) ); // -1

Repetition

RegExp Repetition Syntax
SyntaxMeaning
*Match previous pattern 0 or more times. Same as {0,}.
?Match previous pattern 0 or 1 time. Same as {0,1}.
+Match previous pattern 1 or more times. Same as {1,}.
{n}Match previous pattern exactly n times.
{n,}Match previous pattern n or more times.
{n,m}Match previous pattern n times or up to m times (inclusive).

Note: these will match as far as possible. For non-greedy version, add a ? after them.

// example of regex repetition pattern

const str = "is 278";

// check if contains 1 or more digits
console.log ( str.search( /\d+/ ) ); // 3

// check if contains 4 or more digits
console.log ( str.search( /\d{4}/ ) ); // -1

Alternate and Conditions

RegExp Repetition Syntax
SyntaxMeaning
x|yAlternate. Match either x or y
x(?=y)Match only if x is followed by y
x(?!y)Match only if x is not followed by y
// check if the string contains “water” or “fire”

const str = "some fire";

console.log( str.search( /water|fire/ ) ); // -5

Capture Group, Back Reference

RegExp Repetition Syntax
SyntaxMeaning
(…)Capture. Captured group can be later referenced by /n where n is a digit. \1 is the first captured group.
(?:…)Group, but don't capture.
/nThe nth captured group before. \1 is the first captured group.

For example of capture, see JS: String.prototype.match

JavaScript Basics

  1. JavaScript Basics
  2. Operators
  3. true, false
  4. Branch Control
  5. Loop
  6. Array Basics
  7. Object Basics

Value Types

  1. Value Types
  2. Primitive Value
  3. “typeof” Operator

Variable

  1. let
  2. const
  3. var 👎
  4. var Order 👎
  5. var Scope 👎
  6. Global Variable
  7. Destructuring Assignment

String

  1. String Overview
  2. Template String
  3. String Escape Sequence
  4. Unicode Escape Sequence
  5. Char, Code Unit, Codepoint

Function

  1. Define Function
  2. Arrow Function ⭐
  3. Function Params
  4. “arguments” Object
  5. Rest Params ⭐
  6. Arg Default Value ⭐
  7. Arg Destructure ⭐
  8. f Declaration vs Expression
  9. Closure
  10. f call apply bind
  11. Functional Programing

Object Property

  1. Property Overview
  2. Property Key
  3. Dot vs Bracket Notation
  4. Create/Delete Property
  5. Get/Set Property
  6. Property Existence
  7. Access Property
  8. List Properties
  9. Property Attributes
  10. Getter/Setter
  11. Property Descriptor
  12. Symbol

Object and Inheritance

  1. Object Overview
  2. Object Type
  3. Find Object's Type
  4. Prototype Chain
  5. Check is in Prototype Chain
  6. Get/Set Parent
  7. Show Prototype Chain
  8. Create Object
  9. Object Literal Expr
  10. Create Object with Parent X
  11. Prevent Adding Property
  12. Clone Object
  13. Test Object Equality
  14. Add Method to Prototype

Array

  1. Understand JS Array
  2. Create Array
  3. Sparse Array
  4. Array-Like Object
  5. Array How-To

Constructor/Class

  1. “this” Binding
  2. What's Constructor?
  3. Property Key "prototype"
  4. Operator “new”
  5. Operator “instanceof”
  6. Property Key “constructor”
  7. Class
  8. Keyword “extends”
  9. Keyword “super”

Iterable ⭐

  1. Interface
  2. Iterable
  3. Iterator
  4. Iterator Prototype
  5. for-of Loop
  6. Spread Operator
  7. Generator
  8. Generator Function

Regular Expression

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

Date

  1. Date Tutorial
  2. Compute Date Range

Set Object

  1. Set Object
  2. Union, Intersection, Diff

Map Object

  1. Map Object
  2. Iterate Over Map Object
  3. Convert Object to/from Map
  4. Map Filter
  5. Reverse Key/Value

Number

  1. String to/from Number
  2. Convert Decimal/Hexadecimal
  3. Format Number
  4. Random Number

Misc

  1. Import/Export
  2. Promise
  3. Proxy
  4. Try Catch Throw Finally
  5. ES2015 Features
  6. ES2016, 2017, 2018, 2019
  7. How to Convert ES5 to ES2015
  8. Style Guide
  9. Semicolon Rules
  10. Exclamation Before Function
  11. How to Determine Strict Mode?
  12. x.y.z Associativity
  13. Function Chain
  14. Random Number, Range, Integer, Element
  15. Timing JS Code
  16. Range Function for Array
  17. Tagged Template String
  18. Allowed Characters in Identifier
  19. Encode URL, Escape String

Object Reference

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

Web Dev Tutorials