Wednesday 12 February 2014

Basics of Regular Expressions

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

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

Syntax:
A regular expression could be defined with the RegExp( ) constructor like this:

var pattern = new RegExp(pattern, attributes);
OR
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 multiline matches, respectively.

[...]Any one character between the brackets.
[^...]Any one character not between the brackets.
[0-9]It matches any decimal digit from 0 through 9.
[a-z]It matches any character from lowercase a through lowercase z.
[A-Z]It matches any character from uppercase A through uppercase Z.
[a-Z]It matches any character from lowercase a through uppercase Z.

Examples :
<html>
<body>
<p id="demo">Click the button to do a case-insensitive search for "India" in a string.</p>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction()
{
var str = "Visit India";
var patt1 = /India/i;
var result = str.match(patt1);
document.getElementById("demo").innerHTML=result;
}
</script>
</body>
</html>

<html>
<body>
Global pattern Matching:
Pattern value is added with "/g" which denotes global

Example:
<p id="demo">Click the button to do a global search for "is" in a string.</p>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction()
{
var str = "Is this all there is?";
var patt1 = /is/g;
var result = str.match(patt1);
document.getElementById("demo").innerHTML=result;
}
</script>
</body>

</html>

No comments:

Post a Comment