A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/javascript-regexp-constructor-property/ below:

JavaScript RegExp Constructor Property - GeeksforGeeks

JavaScript RegExp Constructor Property

Last Updated : 05 Aug, 2025

The constructor property of a JavaScript RegExp object returns a reference to the function that created the regular expression. This property typically points to the built-in RegExp function.

JavaScript
// Creating a regular expression
let regex = /test/;

// Checking the constructor property
console.log(regex.constructor === RegExp); 
Key Points Syntax:
regex.constructor
Real-World Examples 1. Verifying the Type of an Object JavaScript
let regex = /hello/;
if (regex.constructor === RegExp) {
    console.log("This is a RegExp object!"); 
}
2. Creating a New Instance Using the Constructor JavaScript
let regex1 = /world/;
let regex2 = new regex1.constructor("hello", "gi");

console.log(regex2); 

The constructor allows the creation of a new RegExp object with the same constructor function as an existing one.

3. Testing the Constructor of Modified Objects JavaScript
let regex = /test/;

// Modifying the prototype
regex.__proto__.constructor = function () {
    console.log("Modified constructor");
};

// Checking the constructor
let newRegex = new regex.constructor(); 

Note: Modifying the constructor is not recommended as it can lead to unexpected behavior.

4. Recreating a Pattern Dynamically JavaScript
let pattern = "abc";
let flags = "gi";

let regex1 = new RegExp(pattern, flags);
let regex2 = regex1.constructor("123", "g");

console.log(regex2); 

Using the constructor, you can dynamically generate new patterns based on existing objects.

Limitations Why Use the Constructor Property? Conclusion

The constructor property is a utility feature in JavaScript’s RegExp objects, enabling dynamic and programmatically controlled regular expression handling. While not a frequently used property, it provides flexibility for advanced tasks in JavaScript programming.

Recommended Links:

RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4