RegExp object in JavaScript

Regular expressions can be created in 2 ways.

  1. /regular-expression/modifiers
  2. new regEx()

Regular expressions using literal expressions

Below example illustrates how to use regular expressions in JavaScript. In this example – we are searching for any letter from a to e.

var data = “Trump hits record”;
var regExp = /([abcde])/g

var match;

while (match = regExp.exec(data))
console.log(“Match “, match[1], “found at”, match.index);

We can have below types of modifiers.

  1. “g” modifier is used when you want to match the pattern at global level (all matches).
  2. “i” modifier is used if you want to match the pattern in case insensitive manner.
  3. “m” modifier is used when you want to match the pattern on multiple lines.

Regular expression object has below methods.

  1. test() – This method returns true if the pattern is found in the string, otherwise it returns false.
  2. exec() – This method returns the first match in the string. If match is not found, it returns null.

Regular expressions using RegExp constructor

When you use constructor, you will have to escape “\” character.

You may also like...