Article
Regular Expressions in JavaScript
Using Regular Expressions in JavaScript
Using regular expressions in JavaScript is so easy that it’s a wonder more people don’t know that it can be done. You can create a regular expression in JavaScript as follows:
var myRE = /regexp/;
Where regexp is the regular expression code, as described above. For example, the following creates the first example regular expression I presented in the previous section, the one that detects the string “JavaScript”:
var myRE = /JavaScript/;
Similarly, here’s how to create the last example:
var myRE = /^(ba|na)+$/;
By default, JavaScript regular expressions are case sensitive and only search for the first match in any given string. By adding the g (for global) and i (for ignore case) modifiers after the second /, you can make a regular expression search for all matches in the string and ignore case, respectively. Here are a few example regular expressions. For each, I've indicated what portion(s) of the string "test1 Test2 TEST3" they would match:
// RegExp // Match(es):
/Test[0-9]+/ // “Test2” only
/Test[0-9]+/i // “test1” only
/Test[0-9]+/gi // “test1”, “Test2”, and “TEST3”
Using a regular expression is easy. Every JavaScript variable containing a text string supports three methods (or functions, if you aren’t used to object-oriented terminology) for working with regular expressions: match(), replace(), and search().
match()
match() takes a regular expression as a parameter and returns an array of all the matching strings found in the string under consideration. If no matches are discovered, then match() returns false. Returning to our original example, let’s say that we wanted a function that can check that a string entered by the user as his or her phone number is of the form (XXX) XXX-XXXX. The following code would do the trick:
function checkPhoneNumber(phoneNo) {
var phoneRE = /^\(\d\d\d\) \d\d\d-\d\d\d\d$/;
if (phoneNo.match(phoneRE)) {
return true;
} else {
alert( “The phone number entered is invalid!” );
return false;
}
}
As a first order of business, this function defines a regular expression. Let’s break it down to understand how it works. The regular expression begins with ^, to indicate that any match must begin at the start of the string. Next is \(, which will just match the opening parenthesis. We prefixed the character with a backslash to remove its special meaning in regular expression syntax (to mark the start of a set of alternatives for matching). As mentioned previously, \d is a special code that matches any digit; thus, \d\d\d matches any three digits. We could have written [0-9][0-9][0-9] to achieve the same effect, but this is shorter. The rest of the pattern should be pretty self-explanatory. \) matches the closing parenthesis, the space matches the space that must be left in the phone number, then \d\d\d-\d\d\d\d matches three digits, followed by a dash, followed by four more digits. Finally, the $ indicates that any match must end at the end of the string.
Incidentally, we could shorten this regular expression to the following, by using another shortcut that we did not mention above. If you can see how this works, you’re a natural!
var phoneRE = /^\(\d{3}\) \d{3}-\d{4}$/;
Our function then checks if phoneNo.match(phoneRE) evaluates to true or false. In other words, it checks whether or not the string contained in phoneNo matches our regular expression (thus returning an array, which in JavaScript will evaluate to true). If a match is detected, our function returns true to certify that the string is indeed a phone number. If not, a message is displayed warning of the problem and the function returns false.
The most common use for this type of function is in validating user input to a form before allowing it to be submitted. By calling our function in the onSubmit event handler for the form, we can prevent the form from being submitted if the information entered is not properly formatted. Here’s a simple example demonstrating the use of our checkPhoneNumber() function:
<form action=”...”
onSubmit=”return checkPhoneNumber(this.phone.value);”>
<p>Enter phone number (e.g. (123) 456-7890):
<input type=text name=phone></p>
<p><input type=submit></p>
</form>
The user will be unable to submit this form unless a phone number has been entered. Any attempt to do so will produce the error message generated by our checkPhoneNumber() function.