We know that regular expression is just string pattern or simple string that describes the sequence of characters for searching something in the specified string. The test() method of any regular expression object returns the Boolean value that indicates whether or not the searched pattern exists in specified string.
The test method can be used as:
[regular expression object].test([specified string])
The following example demonstrates the use of the test method. In the example we will search the word ‘author‘ in entered input string.
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title></title> <script type="text/javascript" src="http://code.jquery.com/jquery-1.7.js"></script> <script type="text/javascript"> function Searched() { var str = $('#txtName').val(); if (/author/.test(str) == true) { alert('Name contains author '); } } </script> </head> <body> <form id="form1"> <div> Enter your name:<input type="text" id="txtName" /> <input type="button" id="btnOk" value="Ok" onclick="Searched();" /> </div> </form> </body> </html>
And the exec() method returns the array of the matched string if the pattern match is found otherwise it will return the null value. The return array contains the three properties: input(source string), index(index of occurrence) and lastIndex (position following the last character in the match.)
In the following example we print the all occurrence of the number 16 in the input string ‘She is 16 years old. She live at 16 avenue road‘.
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title></title> <script type="text/javascript" src="http://code.jquery.com/jquery-1.7.js"></script> <script type="text/javascript"> function Searched() { var sourceString = "She is 16 years old. She live at 16 avenue road."; // Create regular expression pattern with a global flag. var regx = /16/g; var arr; while ((arr = regx.exec(sourceString)) != null) { document.write("<br />"); document.write("Index = " + arr.index); document.write(" Searched Number= " + arr[0]); } } </script> </head> <body> <form id="form1"> <div> <input type="button" id="btnOk" value="Ok" onclick="Searched();" /> </div> </form> </body> </html>
Output will be:
Index = 7 Searched Number= 16
Index = 33 Searched Number= 16
So both methods can be used for the matching, exec returns the array of all matched string and test method returns true if pattern match is found otherwise false.
Great job. very well managed content on this article…