Regular Expressions2. Ignore Case and Global |
|
Join the DiscussionMore of this FeatureAs well as being able to test if some text contains a particular pattern we can also use regular expressions to retrieve all of the occurrences of a particular pattern from within some text and store those patterns within an array. In order to be able to get all of the occurrences we need to specify that our regular expression is to apply globally as otherwise the search for the pattern will stop when the first occurrence is found. We may also want to get the pattern to match regardless of whether the characters are upper or lower case and so we can tell the regular expression to ignore case.
var myString = 'At home the cat sat.';
var re = /at/ig; var fnd = re.exec(myString); return fnd.length + ' occurrences of "at" found'; In our example code this time we add a g after the closing slash of our regular expression definition to define that the expression is to be processed globally and we add an i to tell it to ignore case. The order of these two doesn't matter as long as they are placed after the closing slash. You don't need to specify both of these if only one is required, just specify the one that you need. We next use the exec method to retrieve all occurrences of our expression from within the text passed to it and save the results in an array. In this example our array will have three entries in the results with fnd[0] containing 'At' and the other two entries in the array both containing 'at'. Returning the length of the array identifies the number of times that our regular expression was found in the text. The string object actually contains contains a method that allows us to pass the regular expression as a parameter and achieve the same result. myString.match(re) produces exactly the same array output as re.exec(myString) as the two methods both perform the same processing with the only difference being which object the method belongs to and which object is passed as a parameter. (Similarly myString.search(re) produces the same result as re.test(myString)) |

