Main Page

new RegExp

This code matches the letter
b
in
“blue”
.
Alternatively, you can specify the character code using octal instead of hex by including the octal charac-
ters after a backslash. For example,
b
is equal to octal 142, so this will work:
var sColor = “blue”;
var reB = /\142/;
alert(reB.test(sColor)); //outputs “true”
To represent a character using Unicode, you must specify a four-digit hexadecimal representation of the
character code. So
b
becomes
\u0062
:
var sColor = “blue”;
var reB = /\u0062/;
alert(reB.test(sColor)); //outputs “true”
Note that to use this method of representing characters with the
RegExp
constructor, you still need to
include a second backslash:
var sColor = “blue”;
var reB = new RegExp(“\\u0062”)/;
alert(reB.test(sColor)); //outputs “true”
Additionally, there are a number of predefined special characters, which are listed in the following table:
Character
Description
\t
The tab character
\n
The new line character
\r
The carriage return character
\f
The form feed character
\a
The alert character
\e
The escape character
\c
X
The control character corresponding to
X
\b
Backspace character
\v
Vertical tab character
\0
Null character
All of these characters must also be double-escaped in order to use them with the
RegExp
constructor.
Suppose you want to remove all new line characters from a string (a common task when dealing with
user-input text). You can do so like this:
var sNewString = sStringWithNewLines.replace(/\n/g, “”);
198
Chapter 7
10_579088 ch07.qxd 3/28/05 11:38 AM Page 198


JavaScript EditorFree JavaScript Editor     Ajax Editor


©