HTML and CSS Reference
In-Depth Information
The regular expression object also provides a method called exec . This method returns the
portion of the input string that matches the expression. The following code example illus-
trates this by adding another button and function to use the exec method instead of test :
function CheckStringExec() {
var s = $('#regExString').val();
var regExpression = /^[A-Z,a-z]\d[A-Z,a-z][\s{1}]?\d[A-Z,a-z]\d/;
var results = regExpression.exec(s);
if(results != null)
alert("Valid postal code." + results[0]);
alert("Invalid postal code.");
<button onclick="CheckStringExec();" >Evaluate with Exec</button>
With this button, the expression is evaluated just like it was with the test method, except
the match is returned as a string array. That the return result is a string array is important to
note because using regular expressions can result in multiple matches. If a match isn't made,
the return result will be null. In this example, the results are evaluated by checking whether
the array isn't null; if it's not, the postal code is valid and shown back to the user. If the match
isn't made, the return value will be null.
The string object also provides regular expression methods. The string could be used
directly to evaluate the expression. The string provides the search and match methods. The
search method returns the index of the character in the string where the first match occurred.
The match method returns the part of the string that matches the pattern, much like the exec
method. In addition to these two methods, many of the other string methods accept a regular
expression object, such as indexOf , split , and replace . This provides some advanced functional-
ity for manipulating strings in JavaScript.
The example uses a regular expression to validate user input of data entered into the
webpage. Keep in mind that data can come from anywhere, such as an RSS feed or back-
end server providing JavaScript Object Notation (JSON). In this context, where a website
is expecting specifically formatted data, you can use regular expressions to validate the
incoming data and prevent the possible crashing of the website or at least errors being
presented to users.
Although regular expressions provide a great deal of power in evaluating strings for pat-
terns and ensuring that the data is in the desired format, JavaScript also provides built-in
functions to evaluate the type of data received.
Search WWH ::

Custom Search