Regular Expressions


The last major functional feature of JavaScript is the regular expression. A regular expression as defined by the RegExp constructor is used to carry out pattern matching.

 var country = new RegExp("England"); 

This could have been defined as well using a direct assignment:

 var country = /England/; 

Once a regular expression is defined, we can use it to pattern-match and potentially change strings. The following simple example matches a piece of the string in the variable . geographicLocation and substitutes it for another string.

 var country = new RegExp("England"); var geographicLocation = "New England"; document.write("Destination for work: "+geographicLocation+"<<br />>"); geographicLocation = geographicLocation.replace(country, "Zealand"); document.write("Destination for vacation: "+geographicLocation); 

The result of the execution of this script is shown next .

click to expand

JavaScript s implementation of regular expressions is extremely powerful and very similar to Perl s, so many programmers should be immediately comfortable with JavaScript regular expression facilities. More information on regular expressions can be found in Chapter 8.




JavaScript 2.0
JavaScript: The Complete Reference, Second Edition
ISBN: 0072253576
EAN: 2147483647
Year: 2004
Pages: 209

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net