JS RegExp Objects

JavaScript RegExp Object Properties

Regular Expressions in JavaScript are actually Objects. When you create a pattern (like /hello/g), you are creating an instance of the RegExp object.

Like all objects, RegExp objects contain built-in properties that give you information about the regular expression itself. Let's look at the most useful ones.


1. Flag Properties

You can check whether a specific flag is active on a regular expression by accessing its boolean properties:

Checking Flags Example

const regex = /hello/gi;

console.log(regex.global); // true console.log(regex.ignoreCase); // true console.log(regex.multiline); // false


2. The source Property

The source property returns a string containing the text of the RegExp pattern itself (without the slashes or flags).

The source Property Example

const regex = /[A-Z]+/g;

console.log(regex.source); // Outputs: [A-Z]+


3. The lastIndex Property (Advanced)

The lastIndex property is one of the most important, yet confusing, properties of a RegExp object.

It specifies the index at which to start the next match. However, this property only works if the regular expression has the g (global) or y (sticky) flag set.

When you use a method like exec() or test() to find a match, the RegExp engine automatically updates the lastIndex property to the character immediately following the match it just found. This allows you to call the method again to find the next match in a string!

The lastIndex Property in Action

let text = "cat bat rat";
let regex = /at/g;

console.log("Initial lastIndex:", regex.lastIndex); // 0

regex.test(text); // Matches "cat" console.log("After first match:", regex.lastIndex); // 3 (index after "cat")

regex.test(text); // Matches "bat" console.log("After second match:", regex.lastIndex); // 7 (index after "bat")