JavaScript RegExp source Property
Last Updated :
05 Aug, 2025
The source property of a JavaScript regular expression object returns the text of the pattern used to create the RegExp object, without the enclosing slashes or flags. This property is read-only and reflects the original pattern as a string.
JavaScript
// Creating a regular expression
let regex = /hello\d+/gi;
// Accessing the source property
console.log(regex.source);
Key Points
- Pattern as String: The source property returns the exact text of the pattern, making it ideal for dynamic use or debugging.
- Escaped Characters: Any special characters in the pattern are escaped in the returned string.
- Read-Only: The source property cannot be modified directly.
Syntax:
regex.source
Real-World Examples
1. Extracting the Pattern
JavaScript
let regex = /\d{3}-\d{2}-\d{4}/;
console.log(`Pattern used: ${regex.source}`);
OutputPattern used: \d{3}-\d{2}-\d{4}
This is useful for logging or debugging regular expressions.
2. Reusing a Pattern
JavaScript
let regex = /[a-z]+/gi;
let anotherRegex = new RegExp(regex.source, "i");
// Reuses the pattern with a new flag
console.log(anotherRegex.test("HELLO"));
The source property allows you to reuse a regex pattern dynamically while changing its flags.
3. Building Dynamic Patterns
JavaScript
let pattern = "\\d+";
let regex = new RegExp(pattern, "g");
console.log(regex.source);
console.log("123 456".match(regex));
Output\d+
[ '123', '456' ]
You can dynamically construct patterns using the source property or raw strings.
4. Debugging Regular Expressions
JavaScript
let regex = /(foo|bar)\d*/gi;
console.log(`Debugging pattern: ${regex.source}`);
OutputDebugging pattern: (foo|bar)\d*
By inspecting the source, you can verify the exact regex used in your code.
5. Comparing Regular Expressions
JavaScript
let regex1 = /abc\d+/;
let regex2 = /abc\d+/g;
console.log(regex1.source === regex2.source)
console.log(regex1 === regex2);
The source property helps compare the patterns while ignoring flags or object references.
Why Use the source Property?
- Dynamic Applications: Enables flexible construction of new regular expressions from existing ones.
- Debugging: Helps in inspecting and validating regex patterns during development.
- Pattern Reuse: Facilitates the reuse of patterns in different contexts with new flags or configurations.
Conclusion
The source property is a valuable feature for working with regular expressions in JavaScript, providing insights and enabling dynamic regex manipulation.
Recommended Links:
Explore
JavaScript Basics
Array & String
Function & Object
OOP
Asynchronous JavaScript
Exception Handling
DOM
Advanced Topics