RegExp flags

The literal syntax of regular expressions allows for specific flags, such as i (ignore-case), to be specified after the final delimiting forward slash. These flags will affect the way the regular expression is executed:

/hello/.test('hELlO');  // => false
/hello/i.test('hELlO'); // => true

When using the RegExp constructor, you can pass your flags as the second argument:

RegExp('hello').test('hELlO');      // => false
RegExp('hello', 'i').test('hELlO'); // => true

There are six available flags in JavaScript's flavor of regular expression:

  • i: The ignore-case flag will ignore the case of the string when matching letters (that is, /a/i would match both 'a' andor 'A' in a string).
  • g: The global-match flag will make the regular expression find all matches instead of stopping after the first match.
  • m: The multiline flag will make beginning and end anchors (that is, ^ and $) mark the beginnings and ends of individual lines instead of entire strings.
  • s: The dotAll flag will cause the dot character in your regular expression (which usually only matches non-newline characters) to match newline characters.
  • u: The Unicode flag will treat the sequence of characters in your regular expression as individual Unicode code points instead of code units. This broadly means you can painlessly match and test for rare or exotic symbols such as emojis (see the section within this chapter on the String type to get a more thorough understanding of Unicode).
  • y: The sticky flag will cause all RegExp operations to attempt a match at the exact index detailed by the lastIndex property and then mutate lastIndex upon matches.

As we've seen, regular expressions can also be constructed via the RegExp constructor. This can usefully be invoked as both a constructor or a regular function: either way, you'll receive a RegExp object equivalent to what was derived from the literal syntax:

new RegExp('[a-z]', 'i'); // => /[a-z]/i
RegExp('[a-z]', 'i'); // => /[a-z]/i

This is quite a unique behavior. In fact, the RegExp constructor is the only natively provided constructor that can be invoked as both a constructor and a regular function and, in both cases, returns a new instance. You'll recall that the primitive constructors (such as String and Number) can be invoked as regular functions but will behave differently when invoked as constructors.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.15.226.120