Try my app Expense Manager @ google play and amazon store.

Friday, June 29, 2012

Java Script Tutorial 25 : JavaScript RegExp Object


A regular expression (RegExp) 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 of RegExp is as follow :


var patterntxt=new RegExp(somepattern,modifiers);
or
var patt=/somepattern/modifiers;


In above code, somepattern specifies the pattern of an expression. modifiers specify if a search should be global, case-sensitive, etc.


RegExp Modifiers are used to perform case-insensitive and global searches. For example we use i modifier for case-insensitive matching and g modifier for global match. Global match means, find all matches rather than stopping after the first match. For example 



var str1 = "This is some text.";
var pattern = /some text/i;
document.write(str1.match(pattern));


The result of above case-sensitive search will be : some text 



The test() method searches a string for a specified value, and returns true or false, depending on the result. For example


var pattern=new RegExp("s");
document.write(pattern.test("The sun rises in the east"));


Result of above code will be "true", as it contains the "s" string.


The exec() method searches a string for a specified value, and returns the text of the found value. It return null,  in case no match found. For example


var pattern=new RegExp("s");
document.write(pattern.exec("The sun rises in the east."));


Result of above code will be "s", as it contains the "s" string.

No comments:

Post a Comment

Follow by Email

Google+ Badge