The Tech Works

by on March 26, 2008 · 2 comments

As everyone knows, Scientology gives one superior cognitive skills, as displayed in this brilliant bit of JavaScript:

function validZip(s)
{
if(trim(document.getElementById("M_land").value.toLowerCase()) != "sverige")
{ return(true); }
s = s.replace(/ /g,"");
s = s.replace(/1/g,"0");
s = s.replace(/2/g,"0");
s = s.replace(/3/g,"0");
s = s.replace(/4/g,"0");
s = s.replace(/5/g,"0");
s = s.replace(/6/g,"0");
s = s.replace(/7/g,"0");
s = s.replace(/8/g,"0");
s = s.replace(/9/g,"0");
if(s == "")      { return(true);  }
if(s == "00000") { return(true);  }
return(false);
}

The tech works, as they say.

For non-programmers: this function is supposed to determine whether a given string is a valid zip code. It does this by replacing each digit in the string with a 0, and then seeing if the resulting string is equal to “00000.” If the string contains something other than digits, then this comparison will fail and the function will return false. But Javascript has a native functionality for string pattern matching called regular expressions, so the last 12 lines of this function would be more succinctly expressed with something like:

return s.match(/^\d{5}$/) || s == ""

The expression /^\d{5}$/ means “match any string containing exactly five digits.” The really funny thing about this is that those expressions enclosed by slashes in the “replace” lines of the original function are regular expressions, so whoever wrote this obviously was familiar with regular expressions. He (or she) simply extremely bad at using them.

Hat tip: Lippard

Previous post:

Next post: