String Handling

You'll often want to verify that a string has a certain format—that an email address looks valid, or a date is formatted the way you want, or perhaps that a credit card number passes a basic validity test. There are two ways to verify string formats: using string methods, which break strings apart and analyze them, and using a technique called regular expressions to define patterns of strings as valid or invalid.

Breaking Strings Apart

To verify string formats by breaking them apart, you need these five useful string methods: indexOf(), lastIndexOf(), charAt(), substring(), and split(). I'll cover each method and show how to use them to verify an email address or date. The credit card script is long, so I don't discuss it here, but ...

Get The Book of JavaScript, 2nd Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.