JavaScript RegExp source property is used to return the text of the Regular Expressions. The text returned by this property is the pattern of the Regular Expression without the forward slashes present in the RegExp. If the Regular Expression is empty the text returned by this value is “(?:)”. The escape characters are returned as they are but when it is compared with escape characters it returns an extra forward slash.
Syntax:
Regexpobj.source
Return Type: A string containing the Regexp pattern text without forward slashes.
Example 1: This example prints the RegExp pattern on the console.
Javascript
console.log( new RegExp( "hello learners" ).source); console.log( new RegExp().source); |
Output:
hello learners (?:)
Example 2: This example prints the escape characters on the console and checks their return value
Javascript
const reg1 = new RegExp( "\\t" ); const reg2 = new RegExp( "\n" ); console.log(reg1.source); console.log(reg1.source == "\\t" ); console.log(reg2.source == "\\n" ); |
Output: When compared to the source property add an extra forward slash so that the escape character is not executed on the console. Hence, the comparison returns true.
\t true true
Supported Browsers:
- Chrome
- Edge
- Firefox
- Opera
- Safari
We have a complete list of Javascript RegExp expressions, to check those please go through this JavaScript RegExp Reference article.