Lesson guide

Learning objectives

  • Explain the main purpose of Patterns and flags in JavaScript.
  • Identify the syntax, APIs, or concepts introduced in this lesson.
  • Use the examples to predict how JavaScript will behave before you run similar code.
  • Connect this topic to nearby lessons in Regular expressions.

Real-world context

This lesson matters when you need to recognize where Patterns and flags fits into real JavaScript programs. Regular expressions are patterns that provide a powerful way to search and replace in text.

Key ideas

  • Patterns and flags is part of the Regular expressions chapter, so it builds on the surrounding concepts rather than standing alone.
  • Read each code example in two passes: first for the result, then for the rule that explains the result.
  • When a section compares similar features, focus on the condition that makes you choose one feature over another.

Key terms

  • Patterns and flags
  • Patterns
  • flags
  • Regular expressions
  • JavaScript

Regular expressions are patterns that provide a powerful way to search and replace in text.

In JavaScript, they are available via the RegExp object, as well as being integrated in methods of strings.

Regular Expressions

A regular expression (also “regexp”, or just “reg”) consists of a pattern and optional flags.

There are two syntaxes that can be used to create a regular expression object.

The “long” syntax:

javascript
regexp = new RegExp("pattern", "flags");

And the “short” one, using slashes "/":

javascript
regexp = /pattern/; // no flags
regexp = /pattern/gmi; // with flags g,m and i (to be covered soon)

Slashes /.../ tell JavaScript that we are creating a regular expression. They play the same role as quotes for strings.

In both cases regexp becomes an instance of the built-in RegExp class.

The main difference between these two syntaxes is that pattern using slashes /.../ does not allow for expressions to be inserted (like string template literals with ${...}). They are fully static.

Slashes are used when we know the regular expression at the code writing time – and that’s the most common situation. While new RegExp is more often used when we need to create a regexp “on the fly” from a dynamically generated string. For instance:

javascript
let tag = prompt("What tag do you want to find?", "h2");

let regexp = new RegExp(`<${tag}>`); // same as /<h2>/ if answered "h2" in the prompt above

Flags

Regular expressions may have flags that affect the search.

There are only 6 of them in JavaScript:

iWith this flag the search is case-insensitive: no difference between A and a (see the example below).gWith this flag the search looks for all matches, without it – only the first match is returned.mMultiline mode (covered in the chapter Multiline mode of anchors ^ $, flag "m").sEnables “dotall” mode, that allows a dot . to match newline character \n (covered in the chapter Character classes).uEnables full Unicode support. The flag enables correct processing of surrogate pairs. More about that in the chapter Unicode: flag "u" and class \p{...}.y“Sticky” mode: searching at the exact position in the text (covered in the chapter Sticky flag "y", searching at position)

Colors

From here on the color scheme is:

  • regexp – red
  • string (where we search) – blue
  • result – green

Searching: str.match

As mentioned previously, regular expressions are integrated with string methods.

The method str.match(regexp) finds all matches of regexp in the string str.

It has 3 working modes:

  1. If the regular expression has flag g, it returns an array of all matches:
javascript
let str = "We will, we will rock you";

alert( str.match(/we/gi) ); // We,we (an array of 2 substrings that match)

Please note that both We and we are found, because flag i makes the regular expression case-insensitive.

  1. If there’s no such flag it returns only the first match in the form of an array, with the full match at index 0 and some additional details in properties:
javascript
let str = "We will, we will rock you";

let result = str.match(/we/i); // without flag g

alert( result[0] );     // We (1st match)
alert( result.length ); // 1

// Details:
alert( result.index );  // 0 (position of the match)
alert( result.input );  // We will, we will rock you (source string)

The array may have other indexes, besides 0 if a part of the regular expression is enclosed in parentheses. We’ll cover that in the chapter Capturing groups.

  1. And, finally, if there are no matches, null is returned (doesn’t matter if there’s flag g or not).

This a very important nuance. If there are no matches, we don’t receive an empty array, but instead receive null. Forgetting about that may lead to errors, e.g.:

javascript
let matches = "JavaScript".match(/HTML/); // = null

if (!matches.length) { // Error: Cannot read property 'length' of null
  alert("Error in the line above");
}

If we’d like the result to always be an array, we can write it this way:

javascript
let matches = "JavaScript".match(/HTML/) || [];

if (!matches.length) {
  alert("No matches"); // now it works
}

Replacing: str.replace

The method str.replace(regexp, replacement) replaces matches found using regexp in string str with replacement (all matches if there’s flag g, otherwise, only the first one).

For instance:

javascript
// no flag g
alert( "We will, we will".replace(/we/i, "I") ); // I will, we will

// with flag g
alert( "We will, we will".replace(/we/ig, "I") ); // I will, I will

The second argument is the replacement string. We can use special character combinations in it to insert fragments of the match:

SymbolsAction in the replacement string
$&inserts the whole match
``$```inserts a part of the string before the match
$'inserts a part of the string after the match
$nif n is a 1-2 digit number, then it inserts the contents of n-th parentheses, more about it in the chapter Capturing groups
$<name>inserts the contents of the parentheses with the given name, more about it in the chapter Capturing groups
$$inserts character $

An example with $&:

javascript
alert( "I love HTML".replace(/HTML/, "$& and JavaScript") ); // I love HTML and JavaScript

Testing: regexp.test

The method regexp.test(str) looks for at least one match, if found, returns true, otherwise false.

javascript
let str = "I love JavaScript";
let regexp = /LOVE/i;

alert( regexp.test(str) ); // true

Later in this chapter we’ll study more regular expressions, walk through more examples, and also meet other methods.

Full information about the methods is given in the article Methods of RegExp and String.

Common mistakes

  • Skipping the small examples and then missing the exact rule that Patterns and flags depends on.
  • Copying code without changing one value at a time to see which part controls the result.
  • Treating similar-looking syntax or APIs as interchangeable before checking their edge cases.

Summary

  • A regular expression consists of a pattern and optional flags: g, i, m, u, s, y.
  • Without flags and special symbols (that we’ll study later), the search by a regexp is the same as a substring search.
  • The method str.match(regexp) looks for matches: all of them if there’s g flag, otherwise, only the first one.
  • The method str.replace(regexp, replacement) replaces matches found using regexp with replacement: all of them if there’s g flag, otherwise only the first one.
  • The method regexp.test(str) returns true if there’s at least one match, otherwise, it returns false.

Predict

Before running this RegExp basics block, predict the six output lines. It compares match with and without g, case-insensitive i, the null no-match case, replace with and without g, and test.

javascript
Reveal explanation

With g, match returns all matches, and with i it ignores case, so both We and we are found. Without g, match returns only the first match plus details such as index. A failed match is null, so the block uses || [] before reading .length. replace changes only the first match unless g is present, while test returns a boolean.

Try it

Remove the i flag from the first two regular expressions, then predict the global and first lines. Then remove || [] and explain why reading .length would become unsafe.

Practice

  • Rewrite one example from this lesson without looking at the original, then run it and compare the result.
  • Change one input, operator, method call, or option in a code sample and predict what will happen before running it.
  • Explain Patterns and flags in your own words as if you were reviewing it with another learner.

Keep learning

Continue with Character classes when you are ready for the next lesson.