JS Regular Expression Object

Card image cap

Regular expressions and regular objects

A regular expression is an object that describes a pattern of characters.

The JavaScript RegExp class represents regular expressions, And both String and RegExp define methods that use regular expressions to perform powerful pattern-matching and search-and-replace functions on text.

Syntax:

  var pattern = new RegExp(pattern, attributes);
  var pattern = /pattern/attributes;
  • pattern: A string that specifies the pattern of the regular expression or another regular expression.
  • attributes: An optional string containing any of the "g","i", and "m" attributes that specify global, case-insensitive, and multiline matches, respectively.
  • Bracketts:

    Brackets ([]) have a special meaning when used in the context of regualr expression.

    they are used to find a range of characters.

    • [...] - Any one character between the brackets.
    • [^...] - Any one character not between the brackets.
    • [0-9] - It matches any decimal digit from 0 through 9.
    • [a-z] - it matches any character from lowercase a through lowercase z.
    • [A-Z] - it matches any character from uppercase A through uppercase Z.
    • [a-Z] - It matches any character from lowercase a through uppercase Z.

    Quantifiers:

    The frequency or position of bracketed character sequences and single characters can be denoted by a special character.

    Each special character have a specific connotation. The +,*,?, and $ flags all follow a character sequence.

    • p+ -It matches any string containing at least one p.
    • p* -It matches nay string containing zero or more p's.
    • p? -It matches any string containing one or more p's.
    • p{N} -It matches any string containing a sequence of N p's.
    • p{2,3} -It matches any string containing a sequence of two or three p's.
    • p{2,} -It matches any string containing a sequence of at least two p's.
    • p$ -It matches any string with p at the end of it.
    • ^p -It matches any string with p at the beginning of it.

    • Regular Expression Properties

      Property Description
      Global Specifies if the "g" modifier is set
      ingnoreCase Specifies if the "i" modifies is set.
      LastIndex The index at which to start the next match.
      Multiline Specifies if the "m" modifier is set.
      Source The text of the pattern.
      Global Specifies if the "g" modifier is set.


      Regular Expression Methods

      Property Description
      exec() Executes a search for a match in its string parameter.
      test() Tests for a match in its string parameter.
      toSource() Returns an object literal representing the specified object; you can use this value to create a new object.
      toString() Returns a string representing the specified object.


      Read Also:


    Card image cap