A regular expression is a pattern of characters . JavaScript regular expressions are objects. When you create a regular expression, you test the regular expression against a string. For example, the regular expression /green/ might be matched against the string "The green grass grows" . If green is contained in the string, then there is a successful match. Building a regular expression is like building a string. If you recall, you can create a String object the literal way or you can use the String() constructor method. To build a regular expression object, you can assign a literal regular expression to a variable, or you can use the RegExp constructor to create and return a regular expression object. 13.2.1 The Literal WayTo create a regular expression object with the literal notation, you assign the regular expression to a variable. The regular expression is a pattern of characters enclosed in forward slashes . After the closing forward slash, options may be provided to modify the search pattern. The options are i, g , and m . See Table 13.1. Table 13.1. Options used for modifying search patterns.
FORMAT var variable_name = /regular expression/options; Example: var myreg = /love/; var reobj = /san jose/ig; If you are not going to change the regular expression, say, if it is hard-coded right into your script, then this literal notation is faster, since the regular expression is evaluated at runtime. 13.2.2 The Constructor MethodThe constructor method, called RegExp() , creates a RegExp object. The RegExp() constructor takes one or two arguments. The first argument is the regular expression; it is a string representing the regular expression, for example, "green" represents the literal regular expression /green/ . The second optional argument is called a flag such as i for case insensitivity or g for global. The constructor method is used when the regular expression is being provided from some other place, such as from user input, and may change throughout the run of the program. This method is handled at runtime. FORMAT var variable_name = new RegExp("regular expression", "options"); Example: var myreg = new RegExp("love"); var reobj = new RegExp("san jose", "ig"); Testing the ExpressionThe RegExp object has two methods that can be used to test for a match in a string, the test() method and the exec () method, which are quite similar. The test() method searches for a regular expression in a string and returns true if it matched and false if it didn't. The exec() method also searches for a regular expression in a string. If the exec() method succeeds, it returns an array of information including the search string, and the parts of the string that matched. If it fails, it returns null . This is similar to the match() method of the String object. Table 13.2 summarizes the methods of the RegExp object. Table 13.2. Methods of the RegExp object.
The test() MethodThe RegExp object's test() method is used to see if a string contains the pattern represented in the regular expression. It returns a true or false Boolean value. After the search, the lastIndex property of the RegExp object contains the position in the string where the next search would start. (A string starts at character position 0.) If a global search is done, then the lastIndex property contains the starting position after the last pattern was matched. (See Example 13.4 to see how the lastIndex property is used.) Steps to test for a match:
FORMAT var string="String to be tested goes here"; var regex = /regular expression/; // Literal way var regex =new RegExp("regular expression"); // Constructor way regex.test (string); // Returns either true or false or /regular expression/.test("string"); Example: var myString="She wants attention now!"; var regex = /ten/ // Literal way var regex=new RegExp("ten"); // Constructor way regex.test (myString); // Looking for "ten" in myString or /ten/.test ("She wants attention now!"); Example 13.1<html> <head> <title>Regular Expression Objects the Literal Way</title> <script language = "JavaScript"> 1 var myString="My gloves are worn for wear."; 2 var regex = /love/; // Create a regular expression object 3 if ( regex.test(myString) ){ 4 alert("Found pattern!"); } else{ 5 alert("No match."); } </script> </head><body></body> </html> EXPLANATION
Example 13.2<head> <title>Regular Expression Objects with the Constructor</title> <script language = "JavaScript"> 1 var myString="My gloves are worn for wear."; 2 var regex = new RegExp("love"); // Creating a regular // expression object 3 if (regex.test(myString)){ 4 alert("Found pattern love!"); } else{ 5 alert("No match."); } </script> </head><body></body> </html> EXPLANATION
The exec() MethodThe exec() method executes a search to find a match for a specified pattern in a string. If it doesn't find a match, exec() returns null; otherwise it returns an array containing the string that matched the regular expression. FORMAT array = regular_expression.exec(string); Example: list = /ring/.exec("Don't string me along, just bring me the goods."); Example 13.3<html> <head> <title>The exec() method</title> <script language = "JavaScript"> 1 var myString="My lovely gloves are worn for wear, Love."; 2 var regex = /love/i; // Create a regular expression object 3 var array=regex.exec(myString); 4 if ( regex.exec(myString )){ alert("Matched! " + array); } else{ alert("No match."); } </script> <body></body> </html> EXPLANATION
13.2.3 Properties of the RegExp ObjectThere are two types of properties that can be applied to a RegExp object. The first type is called a class property (see Table 13.3) and applies to the RegExp object as a whole, not a simple instance of a regular expression object. For example, the input property contains the last string that was matched, and is applied directly to the RegExp object as RegExp.input . The other type of property is called an instance property and is applied to an instance of the object (see Table 13.4); for example, mypattern.lastIndex refers to the position within the string where the next search will start for this instance of the regular expression object, called mypattern . Table 13.3. Class properties of the RegExp object.
Table 13.4. Instance properties of the RegExp object.
Example 13.4<html> <head><title>The test() method</title> </head> <body bgcolor=silver> <font face="arial" size="+1"> <script language = "JavaScript"> 1 var myString="I love my new gloves!"; 2 var regex = /love/g; // Create a regular expression object 3 var booleanResult = regex.test(myString); if (booleanResult != false){ 4 document.write("Tested regular expression <em>"+ regex.source + ".</em> The result is <em>" + booleanResult + "</em>"); document.write(".<br>Starts searching again at position " + 5 regex.lastIndex + " in string<em> \"" + 6 RegExp.input + "\"<br>"); document.write("The last matched characters were: "+ 7 RegExp.lastMatch +"<br>"); document.write("The substring preceding the last match is: 8 "+ RegExp.leftContext +"<br>"); document.write("The substring following the last match is: 9 "+ RegExp.rightContext +"<br>"); } else{ alert("No match!"); } </script></body> </html> EXPLANATION
13.2.4 String Methods Using Regular ExpressionsIn addition to the RegExp object's test() and exec() methods, the String object provides four methods that also work with regular expressions. Table 13.5. String object regular expression methods.
The match() MethodThe match() method, like the exec() method, is used to search for a pattern of characters in a string and returns an array where each element of the array contains each matched pattern that was found. If no match is found, returns null . With the g flag, match() searches globally through the string for all matching substrings. FORMAT array = String.match(regular_expression); Example: matchList = "Too much, too soon". match(/too/ig) ; Example 13.5<html> <head> <title>The match() Method</title> </head><body> <font size="+1"><font face="arial, helvetica"> <script language = "JavaScript"> 1 var matchArray = new Array(); 2 var string="I love the smell of clover." 3 var regex = /love/g; 4 matchArray=string.match(regex); 5 document.write("Found "+ matchArray.length +" matches.<br>"); </script> </body> </html> EXPLANATION
The search() MethodThe search() method is used to search for a pattern of characters within a string, and returns the index position of where the pattern was found in the string. The index starts at zero. If the pattern is not found, 1 is returned. For basic searches, the String object's indexOf() method works fine, but if you want more complex pattern matches, the search() method is used, allowing you to use regular expression metacharacters to further control the expression. (See "Getting ControlThe Metacharacters" on page 414.) FORMAT var index_value = String.search(regular_expression); Example: var position = "A needle in a haystack". search(/needle/ ); Example 13.6<html> <head> <title>The search() Method</title> </head><body bgcolor="yellow"> <font size="+1"> <font face="arial, helvetica"> <script language = "JavaScript"> 1 var myString="I love the smell of clover." 2 var regex = /love/; 3 var index=myString.search(regex); document.write("Found the pattern "+ regex+ " at position " +index+"<br>"); </script> </body> </html> EXPLANATION
The replace() MethodThe replace() method is used to search for a string and replace the string with another string. The i modifier is used to turn off case sensitivity and the g modifier makes the replacement global; that is, all occurrences of the found pattern are replaced with the new string. The replace() method is also used with the grouping metacharacters. (See "Grouping or Clustering" on page 442.) FORMAT string = oldstring.replace(regular_expression, replacement_value); Example: var str1 = "I am feeling blue".replace(/blue/, "upbeat"); (str1 is assigned: "I am feeling upbeat.") Example 13.7<html> <head> <title>The replace() Method</title> </head> <body bgcolor="yellow"> <font size="+1"> <font face="arial, helvetica"> <script language = "JavaScript"> 1 var myString="Tommy has a stomach ache." 2 var regex = /tom/i; // Turn off case sensitivity 3 var newString=myString.replace(regex, "Mom"); document.write(newString +"<br>"); </script> </body> </html> EXPLANATION
Figure 13.6. The first occurrence of Tom , uppercase or lowercase, is replaced with Mom.
The split() MethodThe String object's split() method splits a single text string into an array of substrings. In a real-world scenario, it would be like putting little crayon marks at intervals on a piece of string and then cutting the string everywhere a mark appeared, thus ending up with a bunch of little strings. In the JavaScript world, the crayon mark is called a delimiter , which is a character or pattern of characters that marks where the string is to be split up. When using the String object's split() method, if the words in a string are separated by commas, then the comma would be the delimiter and if the words are separated by colons, then the colon is the delimiter. The delimiter can contain more complex combinations of characters if regular expression metacharacters are used. FORMAT array = String.split(/delimiter/); Example: splitArray = "red#green#yellow#blue".split(/#/); (splitArray is an array of colors. splitArray[0] is "red") Example 13.8<html> <head><title>The split() Method</title></head> <body> <font size="+1"> <font face="arial, helvetica"> <script language = "JavaScript"> 1 var splitArray = new Array(); 2 var string="apples:pears:peaches:plums:oranges"; 3 var regex = /:/; 4 splitArray=string.split(regex); // Split the string by colons 5 for(i=0; i < splitArray.length; i++){ document.write( splitArray[i] + "<br>"); } </script> </body> </html> EXPLANATION
Example 13.9<html> <head> <title>The split() Method</title> </head> <font size="+1"> <font face="arial, helvetica"> <script language = "JavaScript"> 1 var splitArray = new Array(); 2 var myString="apples pears,peaches:plums,oranges"; 3 var regex = /[\t:,]/; // Delimeter is a tab, colon, or comma 4 splitArray=myString.split(regex); for(i=0; i < splitArray.length; i++){ 5 document.write( splitArray[i] + "<br>"); } </script> </body> </html> EXPLANATION
|