Greg's Blog

helping me remember what I figure out

JavaScript: Search and Replace (Addendum)

| Comments

Just a brief follow up on the previous article on Search and replace. I mentioned to ward the end that in order to improve the performance of the script I was considering moving the the Regular Expression bit outside of the main script into a separate function. The focus of this article will be calling the new function and returning the value. As ever here is the whole script for you to look at first.

<!DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 4.0 Transitional//EN”>
<html>
<head>
<title>Example match and replace</title>
<script language=”JavaScript1.2”>
function strip(str) {
   var ar = str.match(/(w+)?([^# ]*)/);
   var str = RegExp.$2.replace(/_|’/g, ’ ‘);
   return (str);
}
function validate(f) {
   for (var i=0;i<f.length;i++) {
      e = f.elements[i];
      if(((e.type == “text”) || (e.type == “textarea”)) && !e.optional) {
         if ((e.value == null) || (e.value == “”)) {
         whichEl = eval(“document.all.elField” + i);
         whichEl.innerHTML = strip(e.name);
         }
      }
   }
   return false;
}
</script>
</head>
<body>
<form name=”form1” action=”” method=”post” enctype=”multipart/form-data” onsubmit=”return validate(this);”>
<input type=”Text” name=”r_test1_’test_1’” size=”25”>  <SPAN ID=”elField0”></SPAN><br>
<input type=”Text” name=”r_test2_’test_2’” size=”25”>  <SPAN ID=”elField1”></SPAN><br>
<input type=”Submit” name=”sub_but_2” value=”Submit”>  <SPAN ID=”elField2”></SPAN>
</form>
</body>
</html>

OK now for the changes. Looking at the actual form first I have renamed the function being called on submit to validate(this), hence you will need to rename the main function in your scrip as well. That’s it with the form so now let’s look at the script.

The first thing you will notice is the addition of a function called strip(str) with the parameter str included. This function basically includes the lines of code we used to strip out the “_” and single quotes. As a final step I added the return statement. This was required in order to pass the result of this function back to the calling function, which in this case is validate(f).

The last change we need to make is remove the old stripping code and make sure that the new strip function is being called. To this end you need to locate the line with whichEl.innerHTML = str; and replace str with the function call strip(e.name). You need to pass the parameter e.name, so that strip knows which element to parse.

There you go you are done. When the form is submitted the function validate is called and if one of the fields is empty and error message is generated. To publish this message the script needs to know the field name, which it determines by calling the function strip. That’s it.