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.
You can check whether a specific flag is active on a regular expression by accessing its boolean properties:
global: Returns true if the "g" modifier is set.ignoreCase: Returns true if the "i" modifier is set.multiline: Returns true if the "m" modifier is set.const regex = /hello/gi;console.log(regex.global); // true console.log(regex.ignoreCase); // true console.log(regex.multiline); // false
source PropertyThe source property returns a string containing the text of the RegExp pattern itself (without the slashes or flags).
const regex = /[A-Z]+/g;console.log(regex.source); // Outputs: [A-Z]+
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!
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")