RegExp Syntax

Next ❯String Methods

RegExp syntax consists of pattern and flag(s)

  • turned_in_notSyntax

    RegExp can be declared like :

    /pattern/flags
    OR
    new RegExp("pattern", "flags")
Example:
  • turned_in_notSyntax Sample
    let str = "Hello riya, how are you riya !";
    let pattern = /riya/g;
    str = str.replace(pattern,"john");
    console.log(str);

    It prints on console : "Hello john, how are you john !"

    Comment : It will replace all "riya" with "john" in the string

  • trending_downSyntax Description
    • /riya/g : is a regular expression
    • riya: is a pattern
    • g : is a flag

About Syntax

We match for our pattern in the text/string (basic pattern is just any text),
& flags provides additional functionality and are optional, you can use according to their functionality

You can also put "/pattern/" direct within new RegExp() but must not have any flags with it, like :

new RegExp(/pattern/, "flags")
//Example:
new RegExp(/boy/, "ig")

new RegExp("pattern", "flags") syntax is used mostly when you have dynamic regular expression values


  • String Methods
❮ Prev Getting Started
Next ❯String Methods
TryOut Examples"Learn to Explore..!"

TryOut Editor

receipt