8. Forms and Regular Expressions

Regular expressions are an amazingly powerful way to validate and format text strings. Using regular expressions, you can write a line or two of JavaScript code that can accomplish tasks that otherwise would have taken several dozen lines.

A regular expression (often abbreviated as RegExp or called by its synonym grep) is a pattern, written using special symbols, which describes one or more text strings. You use regular expressions to match patterns of text, so that your script can easily recognize and manipulate text. Like an arithmetic expression, you create a regular expression by using operators, in this case operators that work on text, rather than numbers. There are many regular expression operators, and we’ll look at some of the most common in this chapter. By learning and using these operators, you’ll be able to save yourself a huge amount of effort whenever you need to detect and manipulate text strings.

Regular expressions are also commonly considered to be one of the geekiest parts of programming. You’ve gotten to the point where you think that you have a good grasp of JavaScript, and then you’ll look at a script that contains a regular expression, and it makes no sense at all. If you don’t know the syntax, you don’t have any way of even guessing what’s going on. What does all that gibberish mean?

But the syntax isn’t that hard, so long as you break the gibberish down into small, meaningful pieces (at which point it’s no longer gibberish). In this chapter, we’ll demystify regular expression syntax and discuss how to make your code tighter and more powerful using regular expressions.

Are You Freaking Out Yet?

If this is the first time that you’ve been exposed to regular expressions, chances are you’re feeling a bit intimidated right about now. We’ve included this chapter here because it makes the most sense to use regular expressions to validate form entries. But the rest of the material in this book doesn’t build on this chapter, so if you want to skip on to the next chapter until you’ve got a bit more scripting experience under your belt, we won’t mind a bit.

On the other hand, regular expressions are well worth the investment of your time. They’re not only useful in JavaScript; regular expressions can be used everywhere from other programming languages (such as Perl, Java, Python, and PHP) to Apache configuration files to inside text editors such as BBEdit and TextMate. Even Adobe Dreamweaver and (to a certain extent) Microsoft Word use regular expressions to make search and replace more powerful.


..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.16.167.241