JavaScript RegExp - Overview



A regular expression is an object that describes a pattern of characters.

The JavaScript RegExp class represents regular expressions, and both String and RegExp define methods that use regular expressions to perform powerful pattern-matching and search-and-replace functions on text.

Syntax

A regular expression could be defined with the RegExp () constructor, as follows −

var pattern = new RegExp(pattern, attributes);
or simply
var pattern = /pattern/attributes;

Here is the description of the parameters −

  • pattern − A string that specifies the pattern of the regular expression or another regular expression.

  • attributes − An optional string containing any of the "g", "i", and "m" attributes that specify global, case-insensitive, and multi-line matches, respectively.

Example

Following example shows usage of RegExp to check if a string is present in given text or not.

<html>
   <head>
      <title>JavaScript RegExp</title>
   </head>
   
   <body>
      <script type = "text/javascript">
         var str = "Javascript is an interesting scripting language";
         var re = new RegExp( "script", "g" );
         
         var result = re.test(str);
         document.write("Test 1 - returned value : " +  result); 
         
         re = new RegExp( "pushing", "g" );
         
         var result = re.test(str);
         document.write("<br />Test 2 - returned value : " +  result); 
      </script>
   </body>
</html>

Output

Test 1 - returned value : true
Test 2 - returned value : false 
Advertisements