JavaScript RegExp source Property
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.
// Creating a regular expression
let regex = /hello\d+/gi;
// Accessing the source property
console.log(regex.source);
Output
hello\d+
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
let regex = /\d{3}-\d{2}-\d{4}/;
console.log(`Pattern used: ${regex.source}`);
Output
Pattern used: \d{3}-\d{2}-\d{4}
This is useful for logging or debugging regular expressions.
2. Reusing a Pattern
let regex = /[a-z]+/gi;
let anotherRegex = new RegExp(regex.source, "i");
// Reuses the pattern with a new flag
console.log(anotherRegex.test("HELLO"));
Output
true
The source property allows you to reuse a regex pattern dynamically while changing its flags.
3. Building Dynamic Patterns
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
let regex = /(foo|bar)\d*/gi;
console.log(`Debugging pattern: ${regex.source}`);
Output
Debugging pattern: (foo|bar)\d*
By inspecting the source, you can verify the exact regex used in your code.
5. Comparing Regular Expressions
let regex1 = /abc\d+/;
let regex2 = /abc\d+/g;
console.log(regex1.source === regex2.source)
console.log(regex1 === regex2);
Output
true false
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:
- JavaScript RegExp Complete Reference
- JavaScript Cheat Sheet-A Basic guide to JavaScript
- JavaScript Tutorial