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
regex.sourceReal-World Examples 1. Extracting the Pattern JavaScript
let regex = /\d{3}-\d{2}-\d{4}/;
console.log(`Pattern used: ${regex.source}`);
Pattern 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));
\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}`);
Debugging 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?The source property is a valuable feature for working with regular expressions in JavaScript, providing insights and enabling dynamic regex manipulation.
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