Patterns and Flags

Patterns and Flags

Patterns and Flags


Regular expressions are the patterns, providing a robust means of searching and replacing in the text.

They are available via the Regexp object in JavaScript. Also, they are integrated into the methods of strings.

Regular Expressions

A regular expression ( or a “regexp”, “regex”, “reg”) encompasses a pattern and optional flags.

Two syntaxes (long and short) are used for creating a regular expression object.

The long syntax is the following:

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

The short one uses slashes "/", like this:

regexp = /pattern/; // no flags
regexp = /pattern/gmi; // with flags g,m and i

The slashes /.../ signal JavaScript that a regular expression is being created. The slashes here play the same role, as quotes in strings.

In both of the cases, regexp becomes the built-in RegExp class instance. The difference between the two syntaxes above is that pattern applying slashes, never allows the expressions to be inserted. They are static.

Slashes are applied in case one knows the regular expression at the code writing time. This happens frequently. The new RegExp is used often when it is necessary to generate a regexp “on the fly” from a dynamically created string.

Here is an example:

let tag = prompt("What tag do you want create?", "div");

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

Flags

Regular expressions might also include flags, affecting the search.

Only six flags exist in JavaScript:

  • i: this flag makes the search case-insensitive. There is no difference between B and b.
  • g: with this one, the search investigates all the matches without it. And only the first match is returned.
  • m: this is the multiline mode.
  • s: this flag allows a dot (.) for matching newline character \n.
  • u: with this one, you can enable full Unicode support. It activates the correct processing of surrogate pairs.
  • y: it is the “sticky” mode, allowing you to search the exact position in the text.

As for the color theme, it will be as follows:

Red for regexp.

Blue for the string.

Green for the result.

Searching: str.match

Regular expressions may also be integrated with string methods.

The str.match(regexp) method uncovers the matches of regexp inside the string str.

Three working modes are actual for it:

  1. In case the regexp has the g flag, an array of matches will be returned by it, like this:

let str = "Welcome to Web"; 

console.log(str.match(/welcome/gi)); // Welcome (an array of two matching substrings)

  1. In this case, both You and you are found. Notice that the i flag makes the regexp case-insensitive.

  2. In case, no such flag exists, it returns only the first match in the array form, along with the full match at index 0, as well as several additional details in the properties. Here is an example:

let str = "Welcome to Web";

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

console.log(result[0]); // Welcome(1st match)

console.log(result.length); // 1

// Details:

console.log(result.index); // 0 (position of the match)

console.log(result.input); // Welcome to Web

The array can include other indexes, in addition to 0, in case the regexp is enclosed in parentheses.

Finally, in case no matches are found, null is returned ( not matter, there is g flag or not). So, if there is no match, you won’t get an empty array, but null . It is an essential point. Not taking this into account will lead to an error. Here is an example:

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

if (!matches.length) { // Error: Can’t read property 'length' of null

  console.log("Error in the line");

}

In case you want the result to always be an array, then you should write it like this:

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

if (!matches.length) {

  console.log("No matches"); // now it works

}

Replacing: str.replace

The str.replace(regexp, replacement) method is targeted at replacing the matches found using regexp in string str along with the replacement .

Here is an example of using str.replace(regexp, replacement):

// no flag g

console.log("It's a HTML book, it's a html book".replace(/html/i, "Javascript"));

// with flag g

console.log("It's a HTML book, it's a html book".replace(/html/ig, "Javascript"));

The replacement is the second argument. Special character combinations can be used for inserting fragments of the match in it, like this:

SymbolsThe Action within the replacement string
$&inserting the total match
$inserting a part of the string before matching
$'inserting a string part after the match
$nin case n is a 1-2 digit number, then it will insert the contents of n-th parentheses.
$<name>inserting the contents of the parentheses with the specific name.
$$inserting the character $


An example with the usage of $& will look like this:

console.log("Welcome to Web".replace(/Web/, "$& and Javascript book")); // Welcome to W3Docs and JavaScript book

Testing: regexp.test

The regexp.test(str) method searches for at least a single match. In case of finding it, true is returned, in case of not founding - false .

Here is an example of using regexp.test(str) method:

let str = "Welcome to Web";

let regexp = /TO/i;

console.log(regexp.test(str)); // true

Summary

Regular expressions are a super-handy way of describing patterns in the string data. They can be used for checking a string for characters ( for instance, to look for an email address) by matching the pattern, described in the regular expression.

So, a regular expression encompasses patterns and flags. Flags are optional. Among them are g, i, m, u, s, y.

The search by the regexp without flags and special symbols is similar to a substring search.

The str.match(regexp) method is used to search for matches. The str.replace(regexp, replacement) method replaces the found matches using regexp with replacement. Finally, the regexp.test(str) method returns true after finding at least one match, otherwise- false.

Reactions

Post a Comment

0 Comments

close