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 the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.