Case and Negation in JavaScript Regular Expressions
(Page 1 of 5 )
Welcome to the third part of a five-part series that examines the use of regular expressions in JavaScript. In this part, we'll look at the effects of case sensitivity, how to use negation, and more.
Case Sensitivity for Individual Characters
The following will not produce a match:
/Dog/.test("I have a dog")
while the following produces a match:
/DOg/i.test("I have a dog")
A match is produced in the second case because of the i flag at the end of the regexp.
With the i flag, you make each of the characters in the regexp case insensitive. There may come a time when you want to make only a particular character in the regexp case insensitive. The solution is to put both the upper and lowercase characters in a class (square brackets).
Consider the following two available strings:
var availablestring = "He said, Yes"
and
var availablestring = "He said, 'yes'"
Imagine that the above available strings were typed by two different users of your web page, at different times. You might want to know if the word "yes" was typed. The first user typed "yes" beginning with a capital letter; the second user typed it in quotes, with all letters in lowercase. You might want to know if the word "yes" was typed, independent of whether it began with "Y" or "y." The following code (solution) will produce a match:
/[Yy]es/.test(availablestring)
Negation
Character ranges and some special regexp characters can be negated.
Any character except a digit is written as
[^0-9]
This refers to all characters that are not in the range 0-9. The following code produces a match:
/[^0-9]/.test("12P34")
P is not in the range [0-9]; P is outside. Concerning all characters, P is in the range [^0-9]. Note the presence and absence of the '^' character between the classes [0-9] and [^0-9].
The special character used for negation is "^".
The range outside [a-z] is [^a-z]. That is [^a-z] is the negation of [a-z].
The range outside [A-Z] is [^A-Z]. That is [^A-Z] is the negation of [A-Z].
We shall see other negations below.
Next: Abbreviations for Common Character Classes >>
More JavaScript Articles
More By Chrysanthus Forcha