
| So far we've only really covered pattern matching, so
what do you do with them? The Regular Expression Methods allow us to use
pattern matching to do useful things like searching, matching, and
replacing information.
NOTE: A RegExp Object is automatically created when you assign a string pattern to a variable. The String Object's search() Method is the simplest of all the operations.
search() simply looks through the String specified and returns to index the position of the first matching character sequence in the String. NOTE: the String ignores the global switch 'g' in a Regular Expression literal and that this index value begins at 0 as line 4 demonstrates. If a match is not found, search() returns -1. The split() Method has been in the language since JavaScript 1.1, but with version 1.2 came support for it to take a regular expression argument.
split() takes a string and returns an Array of string elements. Each element exists in the original string separated by characters matching the pattern sent to split() as its argument. The replace() Method returns a brand new string that contains a copy of the original string with any matching part of it replaced accordingly.
NOTICE the use of the gi (global and case-insensitive) switches, without them newStr would be assigned "I'm sad. You're Happy". The example below illustrates another feature of replace() that we can also make use of.
NOTICE that $1 and $3 correspond to "I am" and "You are" respectively and are swapped accordingly by replace(). The RegExp Object has similar properties called $1, $2. etc up to $9, equivalent to \1, etc... which can be fed back into replace(). match(), is very similar to split() except that array element 0 is the entire "original" string.In the case that the Regular Expression does not contain the global switch, the first element of the Array will always return the match for the complete expression while subsequent elements will hold $1, $2, etc.
So in this example,
etc.... test() is very similar to the search() Method. It simply returns returns true if there is a match or false if not.
If the pattern has the global flag set, it will set the lastIndex Property of the RegExp Object and continue the search from that point in the string when called again. NOTE: If it does not have the flag set, lastIndex will be reset to 0. The code to validate the number you've been looking at would like this:It's much simpler than trying to do some indexOf()s and calculating the lengths of each bit. exec() acts in a way similar to match() when the global switch is not used.
exec() populates all the static properties of the RegExp Object, the reg Object and updates details of the Array too. exec() also behaves the same as test() with respect to the global flag being set. Should it not find a match, exec() returns null for the Array. |