HTML and CSS Reference
In-Depth Information
section discusses how to use the JavaScript framework to perform pattern matching with
regular expressions.
Evaluating regular expressions in JavaScript
Just like with strings and integers, regular expressions are objects in JavaScript. As such, they
can be created and can provide methods to evaluate strings. Regular expression objects are
created in a similar fashion as strings; however, rather than use “ to encapsulate the expres-
sion, use the forward slash /<expression>/ instead. JavaScript knows that text surrounded
by forward slashes in this way is a regular expression object. Going back to the postal code
example, the following HTML is provided:
<script type="text/javascript">
function CheckString() {
try{
var s = $('#regExString').val();
var regExpression = /^[A-Z,a-z]\d[A-Z,a-z][\s{1}]?\d[A-Z,a-z]\d/;
if (regExpression.test(s))
alert("Valid postal code.");
else
alert("Invalid postal code.");
} catch (e) {
alert(e.message);
}
}
</script>
<body>
<form>
<input type="text" id="regExString" />
<button onclick="CheckString();" >Evaluate</button>
</form>
</body>
This HTML provides a very basic page with a text box and a button. The button does noth-
ing more than call a function to validate whether the entered text matches the format desired
for a postal code. This page shouldn't contain anything that you haven't seen already, except
the line in which the regular expression object is created:
var regExpression = /^[A-Z,a-z]\d[A-Z,a-z][\s{1}]?\d[A-Z,a-z]\d/;
With this line, a regular expression object is created and, as a result, methods are avail-
able. The string is extracted from the text box and passed to the test method of the regular
expression. The test method returns a Boolean to indicate whether the input string matches
the regular expression that was created.
 
Search WWH ::




Custom Search