Regular Expression Literals
In this lesson, let's see how regex work in JavaScript.
We'll cover the following...
We'll cover the following...
JavaScript supports regular expressions through the RegExp
type and provides a simple syntax to create them, as shown in the Listing below:
Listing: Using RegExp
in JavaScript
<!DOCTYPE html> <html> <head> <title>Regular expression literals</title> <script> var pattern = /[A-Z]{3}-\d{3}/gi; var text = "AB-123 DEF-234 ert-456 -34"; console.log(pattern.test(text)); pattern.lastIndex = 0; var matches; do { matches = pattern.exec(text); console.log(matches); } while (matches != null); </script> </head> <body> Listing 7-5: View the console output </body> </html>
📜NOTE: If you are familiar with regular expressions, you can skip this section. If you would like to get more information about using them, I suggest you to start at http://www.regular-expressions.info/quickstart.html.
How it works
The first line of the script (line six) of this short code defines the pattern
variable as a regular expression.
var pattern =
...