What is RegExp?
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.
Regular expressions are used to perform powerful pattern-matching and "search-and-replace" functions on text.
Syntax
var patt=new RegExp(pattern,modifiers);
or more simply:
var patt=/pattern/modifiers;
or more simply:
var patt=/pattern/modifiers;
- pattern specifies the pattern of an expression
- modifiers specify if a search should be global, case-sensitive, etc.
RegExp Modifiers
Modifiers are used to perform case-insensitive and global searches.The i modifier is used to perform case-insensitive matching.
The g modifier is used to perform a global match (find all matches rather than stopping after the first match).
test()
The test() method searches a string for a specified value, and returns true or false, depending on the result.The following example searches a string for the character "e":
Example
var patt1=new RegExp("e");
document.write(patt1.test("The best things in life are free"));
Since there is an "e" in the string, the output of the code above
will be:document.write(patt1.test("The best things in life are free"));
true
<html>
<body>
<script
type="text/javascript">
var patt1=new
RegExp("e");
document.write(patt1.test("The
best things in life are free"));
</script>
</body>
</html>
exec()
The exec() method searches a string for a specified value, and returns the text of the found value. If no match is found, it returns null.The following example searches a string for the character "e":
Example 1
var patt1=new RegExp("e");
document.write(patt1.exec("The best things in life are free"));
Since there is an "e" in the string, the output of the code above
will be:document.write(patt1.exec("The best things in life are free"));
e
<html>
<body>
<script
type="text/javascript">
var patt1=new
RegExp("e");
document.write(patt1.exec("The
best things in life are free"));
</script>
</body>
</html>
No comments:
Post a Comment