Testing, Reading, and Replacing Text with Regular Expressions

This next bit relates to something we saw in Chapter 6 when we looked at form elements. We're going do something more useful with our code. In this first example, we have a simple contact form—a single phone number. We want to make sure our phone number is formatted in a certain way, like this: (111) 222-3333. You can certainly do this with the JavaScript functions indexOf and lastIndexOf, but it's much easier to do with regular expressions.

There are two methods (in addition to the exec method we saw earlier) you can use to see whether a string matches the pattern or not

regExpObject.test(string) (returns true or false)

string.search(regExpObject) (returns character position of where ...

Get Advanced JavaScript™: Insights and Innovative Techniques 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.