Categories:

Sample Usage

Now that you’ve been introduced to regular expressions and patterns, let’s look at a few examples of common validation and formatting functions.

- Valid Number

A valid number value should contain only an optional minus sign, followed by digits, followed by an optional dot (.) to signal decimals, and if it's present, additional digits. A regular expression to do that would look like this:

var anum=/(^-*\d+$)|(^-*\d+\.\d+$)/

- Valid Date Format

A valid short date should consist of a 2-digit month, date separator, 2-digit day, date separator, and a 4-digit year (e.g. 02/02/2000). It would be nice to allow the user to use any valid date separator character that your backend database supported such as slashes, dashes and periods. You want to be sure the user enters the same date separator character for all occurrences. The following function returns true or false depending on whether the user input matches this date format:

function checkdateformat(userinput){
	var dateformat = /^\d{1,2}(\-|\/|\.)\d{1,2}\1\d{4}$/
	return dateformat.test(userinput) //returns true or false depending on userinput
}

This example uses backreferencing to ensure that the second date separator matches the first one.

- Replace HTML tags (brackets) with entities instead

User input often times must be parsed for security or to ensure it doesn't mess up the formatting of the page. The most common task is to remove any HTML tags (brackets) entered by the user, and replace them with their entities equivalent instead. The following function does just that- replace "<" and ">" with "&lt;" and "&gt;", respectively:

function htmltoentity(userinput){
	var formatted=userinput.replace(/(<)|(>)/g,
	function(thematch){if (thematch=="<") return "&lt;"; else return "&gt;"})
}

The first parameter of  replace() searches for a match for either "<" or ">". The second parameter demonstrates something new and interesting- you can actually use a function instead of a plain replacement text as the parameter. When a function is used, the parameter of it (in this case, "thematch") contains the matched substring and returns what you wish it to be replaced with. Since we're looking to replace both "<" and ">", this function will help us return two different replacement strings accordingly.

And with that this tutorial concludes. As you can see, Regular Expressions really isn't that difficult to understand, with a little time and practice that is!

This tutorial is written by Karen Gayda. Modified by JavaScriptKit.com for structure and added additional content plus examples. Karen Gayda is a Senior Software Engineer in the Internet Services Division at Stellcom Technologies located in San Diego, CA.