Chapter 2. Using Regular Expressions
2.0. Introduction
Regular expressions are search patterns that can be used to find
text that matches a given pattern. For instance, in the last chapter, we
looked for the substring Cookbook within a longer
string:
var testValue = "This is the Cookbook's test string"; var subsValue = "Cookbook"; var iValue = testValue(subsValue); // returns value of 12, index of substring
This code snippet worked because we were looking for an exact match. But what if we wanted a more general search? For instance, we want to search for the words Cook and Book, in strings such as “Joe’s Cooking Book” or “JavaScript Cookbook”?
When we’re looking for strings that match a pattern rather than an
exact string, we need to use regular expressions. We can try to make do
with String functions, but in the end, it’s actually
simpler to use regular expressions, though the syntax and format is a
little odd and not necessarily “user friendly.”
Recently, I was looking at code that pulled the RGB values from a
string, in order to convert the color to its hexadecimal format. We’re
tempted to just use the String.split
function, and split on the commas, but then you have to strip out the
parentheses and extraneous whitespace. Another consideration is how can we
be sure that the values are in octal format? Rather than:
rgb (255, 0, 0)
we might find:
rgb (100%, 0, 0)
There’s an additional problem: some browsers return a color, such as a background color, as an RGB value, others as a hexadecimal. ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access