Cleaning Up Form Entries

Welcome to our free Advanced JavaScript Programming tutorial. This tutorial is based on Webucator's Advanced JavaScript Programming course.

Contact Us or call 1-877-932-8228
Cleaning Up Form Entries

Cleaning Up Form Entries

It is sometimes nice to clean up user entries immediately after they are entered. This can be done using a combination of regular expressions and the replace() method of a string object.

The replace() Method Revisited

Earlier, we showed how the replace() method of a string object can be used to replace regular expression matches with a string. The replace() method can also be used with backreferences to replace a matched pattern with a new string made up of substrings from the pattern. The example below illustrates this.

Code Sample:

<meta charset="UTF-8">
<title>ssn Cleaner</title>
<script type="text/javascript">
var reSSN = /^(\d{3})[\- ]?(\d{2})[\- ]?(\d{4})$/;

function cleanSsn(ssn){
	if (reSSN.test(ssn)) {
		var cleanedSsn = ssn.replace(reSSN, "$1-$2-$3");
		return cleanedSsn;
	} else {
		alert("INVALID SSN");
		return ssn;
	<form onsubmit="return false;">
		<input type="text" name="ssn" size="20">
		<input type="button" value="Clean SSN" 
			onclick="this.form.ssn.value = cleanSsn(this.form.ssn.value);">

Code Explanation

The cleanSsn() function is used to "clean up" a social security number. The regular expression contained in reSSN, ^(\d{3})[\- ]?(\d{2})[\- ]?(\d{4})$, contains three subexpressions: (\d{3}), (\d{2}), and (\d{4}). Within the replace() method, these subexpressions can be referenced as $1, $2, and $3, respectively.

When the user clicks on the "Clean SSN" button, the cleanSsn() function is called. This function first tests to see that the user-entered value is a valid social security number. If it is, it then cleans it up with the line of code below, which dash-delimits the three substrings matching the subexpressions.

var cleanedSsn = ssn.replace(reSSN, "$1-$2-$3");

It then returns the cleaned-up social security number.


This tutorial is based on Webucator's Advanced JavaScript Programming Course. We also offer many other JavaScript Training courses. Sign up today to get help from a live instructor.