Java Reference
In-Depth Information
The forward slashes (/) mark the start and end of the regular expression. This is a special syntax that
tells JavaScript that the code is a regular expression, much as quote marks defi ne a string's start and end.
Don't worry about the actual expression's syntax yet (the \b'|'\b) — that will be explained in detail
shortly.
Alternatively, you could use the RegExp object's constructor function RegExp() and type the following:
var myRegExp = new RegExp(“\\b'|'\\b”);
Either way of specifying a regular expression is fi ne, though the former method is a shorter, more effi cient
one for JavaScript to use and therefore is generally preferred. For much of the remainder of the chapter,
you'll use the fi rst method. The main reason for using the second method is that it allows the regular
expression to be determined at runtime (as the code is executing and not when you are writing the code).
This is useful if, for example, you want to base the regular expression on user input.
Once you get familiar with regular expressions, you will come back to the second way of defi ning them,
using the RegExp() constructor. As you can see, the syntax of regular expressions is slightly different
with the second method, so we'll return to this subject later.
Although you'll be concentrating on the use of the RegExp object as a parameter for the String object's
split(), replace(), match(), and search() methods, the RegExp object does have its own methods
and properties. For example, the test() method enables you to test to see if the string passed to it as
a parameter contains a pattern matching the one defi ned in the RegExp object. You'll see the test()
method in use in an example shortly.
Simple Regular Expressions
Defi ning patterns of characters using regular expression syntax can get fairly complex. In this section you'll
explore just the basics of regular expression patterns. The best way to do this is through examples.
Let's start by looking at an example in which you want to do a simple text replacement using the
replace() method and a regular expression. Imagine you have the following string:
var myString = “Paul, Paula, Pauline, paul, Paul”;
and you want to replace any occurrence of the name “Paul” with “Ringo.”
Well, the pattern of text you need to look for is simply Paul. Representing this as a regular expression,
you just have this:
var myRegExp = /Paul/;
As you saw earlier, the forward-slash characters mark the start and end of the regular expression. Now
let's use this expression with the replace() method.
myString = myString.replace(myRegExp, “Ringo”);
You can see that the replace() method takes two parameters: the RegExp object that defi nes the pat-
tern to be searched and replaced, and the replacement text.
Search WWH ::




Custom Search