Java Reference
In-Depth Information
Let's think about the problem again. You want the pattern to match VBScript or JavaScript. Clearly
they have the Script part in common. So what you want is a new word starting with Java or starting
with VB; either way, it must end in Script.
First, you know that the word must start with a word boundary.
\b
Next you know that you want either VB or Java to be at the start of the word. You've just seen that
in regular expressions | provides the “or” you need, so in regular expression syntax you want the
following:
\b(VB|Java)
This matches the pattern VB or Java. Now you can just add the Script part.
\b(VB|Java)Script\b
You r fi nal code looks like this:
var myString = “JavaScript, VBScript and Perl”;
var myRegExp = /\b(VB|Java)Script\b/gi;
myString = myString.replace(myRegExp, “xxxx”);
alert(myString);
Reusing Groups of Characters
You can reuse the pattern specifi ed by a group of characters later on in the regular expression. To refer
to a previous group of characters, you just type \ and a number indicating the order of the group. For
example, the fi rst group can be referred to as \1, the second as \2, and so on.
Let's look at an example. Say you have a list of numbers in a string, with each number separated by a
comma. For whatever reason, you are not allowed to have two instances of the same number in a row,
so although
009,007,001,002,004,003
would be okay, the following:
007,007,001,002,002,003
would not be valid, because you have 007 and 002 repeated after themselves.
How can you fi nd instances of repeated digits and replace them with the word ERROR? You need to use
the ability to refer to groups in regular expressions.
First, let's defi ne the string as follows:
var myString = “007,007,001,002,002,003,002,004”;
Search WWH ::




Custom Search