Ajax software
Free javascripts
↑
Main Page
The simple web page contains JavaScript code.
The JavaScript variable
myRegExp
is assigned the literal regular expression pattern
L
, using the following
declaration and assignment statement:
var myRegExp = /L/;
In JavaScript, the forward slash is used to delimit a regular expression pattern in a way similar to how
paired quotes are used to delimit a string. There is an alternate syntax, which is not discussed here.
When you click the button labeled Click Here to Enter Text, the
ShowPrompt()
function is called.
The
entry
variable is used to collect the string you enter in the prompt box:
var entry = prompt(“This script tests for matches for the regular expression
pattern: “ + myRegExp + “.\nType in a string and click on the OK button.”, “Type
your text here.”);
The output created depends on whether or not the text you entered contains a match for the regular expres-
sion pattern. Once the text has been entered and the OK button clicked, an
if
statement is executed, which
checks whether or not the text you entered (and which is stored in the
entry
variable) contains a match for
the regular expression pattern stored in the variable
myRegExp
:
if (Validate(entry)){
The
if
statement causes the
Validate
function to be called:
function Validate(entry){
return myRegExp.test(entry);
} // end function Validate()
The
test()
method of the
myRegExp
variable is used to determine whether or not a match is present.
If the
if
statement
if (Validate(entry))
returns the Boolean value
true
, the following code is executed
alert(“There is a match!\nThe regular expression pattern is: “ + myRegExp + “.\n
The string that you entered was: ‘“ + entry + “‘.”);
and uses the
myRegExp
and
entry
variables to display the regular expression pattern and the string that
you entered, together with explanatory text.
If there is no match, the following code is executed, because it is contained in the
else
clause of the
if
statement:
alert(“There is no match in the string you entered.\n” + “The regular expression
pattern is “ + myRegExp + “\n” + “You entered the string: ‘“ + entry + “‘.” );
316
Appendix A: Simple Regular Expressions
bapp01.qxd:bapp01 10:47 316
Ajax software
Free javascripts
→