JavaScript RegExp source property

The JavaScript source property is used to get the text or string of the Regular Expression pattern. For example:

HTML with JavaScript Code
<!DOCTYPE html>
<html>
<body>

   <p id="res"></p>

   <script>
      let myString = "I live in St. Louis";
      let myPattern = /is/gi;
      document.getElementById("res").innerHTML = myPattern.source;
   </script>
   
</body>
</html>
Output

A regular expression is defined in this code by the forward slash (/), which is a way to describe a pattern of characters to match in a string. The variable "myPattern" is assigned the regular expression.

let myPattern = /is/gi;

The regular expression "/is/gi" is made up of two parts: "g" and "i." With the "g" option, the regular expression will match all occurrences of the pattern in the string, not just the first one. The "i" option indicates that the matching should be case-insensitive, which means that both uppercase and lowercase versions of the pattern should match.

The word "is" serves as the regular expression pattern. This means that any instance of the characters "is" in a string will be matched by the regular expression.

The "source" property of the regular expression object is accessed after the regular expression has been defined using the dot (.) notation. The text of the regular expression pattern is stored as a string in the "source" property.

document.getElementById("res").innerHTML = myPattern.source;

The resultant string, "is", is then assigned to the innerHTML property of an HTML element with the ID "res". Therefore, the text "is" will be displayed within the p tag with ID "res" when the code is executed.

JavaScript source Syntax

The syntax of the source property in JavaScript is:

RegExpObj.source

It returns a string representing the textual part of the specified regular expression pattern.

Advantages of the "source" property in JavaScript RegExp

Disadvantages of the "source" property in JavaScript RegExp

JavaScript Online Test


« Previous Tutorial CodesCracker.com »


Liked this post? Share it!