Sunday 2 February 2014

Regular Expression Object

Regular Expressions

·         A regular expression is an object that describes a pattern of characters.
·         When you search in a text, you can use a pattern to describe what you are searching for.
·         A simple pattern can be one single character.
·         A more complicated pattern can consist of more characters, and can be used for parsing, format checking, substitution and more.
·          These are used to check and validate string type data. Called as objects because it
provides methods. It is two types, Static or Dynamic.
Ex : var name;
var exprs=new RegExp(“^[A-Z|a-z]”);
exprs.match(name)  True or False.
It specify that ‘name’ can start with any alphabet.
The JavaScript RegExp class represents regular expressions, and both String and RegExpdefine 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 like this:
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 multiline matches, respectively.
Brackets:
Brackets ([]) have a special meaning when used in the context of regular expressions. They are used to find a range of characters.

<!DOCTYPE html>
<html>
<body>

<p id="demo">Click the button to do a case-insensitive search for "Sr engi" in a string.</p>

<button onclick="myFunction()">Try it</button>

<script>
function myFunction()
{
var s = "Visit SR Eng";
var p = /SR Eng/i;
var result = s.match(p);
document.getElementById("demo").innerHTML=result;
}
</script>

</body>

<!-- http://improvejavascript.blogspot.in/-->
</html>

Ex2:
<!DOCTYPE html>
<html>
<body>

<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>

<!-- http://improvejavascript.blogspot.in/ -->
</html>

Ex3:
<!DOCTYPE html>
<html>
<body>

<script>
var patt1=new RegExp("e");

document.write(patt1.exec("The best things in life are free"));
</script>

</body>

<!-- http://improvejavascript.blogspot.in/ -->
</html>

Ex4:
<!DOCTYPE html>
<html>
<body>

<script>
var p=new RegExp("e");

document.write(p.test("The best things in life are free"));
</script>

</body>

<!-- http://improvejavascript.blogspot.in/ -->
</html>

No comments:

Post a Comment