JavaScript Tutorial (Intermediate Level)

Calling A Rose by Any Other Name

by Gidget Pizzashorts (also known as Dori Smith)

Recommended prerequisite knowledge: how HTML forms work; JavaScript variables, basic arrays, events. What you will learn: string handling, arrays, error checking, and form validation.


In the children's book "Captain Underpants and the Perilous Plot of Professor Poopypants," written by Dav Pilkey, an evil professor forces the characters to assume new names that are based on their current names. Well, I'm no evil professor, but I can show you how to use the following script to get your own, new, silly name.

Your silly name is found by taking the first letter of your first name, the first letter of your last name, and the last letter of your last name, and looking each up on a chart. The first letter of your first name gives you your new first name, and the two letters from your last name give you the first and second parts of your new silly last name.

Let's use Al Gore as our first example. The "A" in Al turns into a new first name of "stinky," and the "G" and "E" from Gore produce "lizard" and "tush," respectively. So, Al Gore's new name is "Stinky Lizardtush." For George Bush, on the other hand, his "G" turns into "fluffy," his "B" to "toilet," and his final "H" converts to "shorts," for a new silly name of "Fluffy Toiletshorts." Calling a rose by any other name, in this case, would give you "Loopy."

It's a pain to convert names by hand, though, isn't it? Sounds like a job for a scripting language! Here's how our JavaScript does its work.

First, we start by creating three arrays--firstName, lastName1, and lastName2. Each of these contains the 26 silly names from that column in the chart.

firstName = new Array("Stinky", "Lumpy", "Buttercup", "Gidget", "Crusty", "Greasy", "Fluffy", "Cheeseball", "Chim-Chim", "Poopsie", "Flunky", "Booger", "Pinky", "Zippy", "Goober", "Doofus", "Slimy", "Loopy", "Snotty", "Falafel", "Dorkey", "Squeezit", "Oprah", "Skipper", "Dinky", "Zsa-Zsa")

lastName1 = new Array("Diaper", "Toilet", "Giggle", "Bubble", "Girdle", "Barf", "Lizard", "Waffle", "Cootie", "Monkey", "Potty", "Liver", "Banana", "Rhino", "Burger", "Hamster", "Toad", "Gizzard", "Pizza", "Gerbil", "Chicken", "Pickle", "Chuckle", "Tofu", "Gorilla", "Stinker")

lastName2 = new Array("head", "mouth", "face", "nose", "tush", "breath", "pants", "shorts", "lips", "honker", "butt", "brain", "tushie", "chunks", "hiney", "biscuits", "toes", "buns", "fanny", "sniffer", "sprinkles", "kisser", "squirt", "humperdinck", "brains", "juice")

Then, down in the <BODY> area, we add a form. The form contains entry fields for the first name (fName) and the last name (lName). When the visitor clicks on the submit button, the onSubmit handler in the <FORM> tag is triggered, calling the function getSillyName() and passing it a value. This is a JavaScript keyword that changes its value based on the context it's used in. In this case, this refers to the form object.

Now it's time to do the actual work, which is handled by the getSillyName() function. This function is passed one parameter, a form object, which will be referred to as myForm inside the function.

By looking at myForm.fName.value, you can find whatever the user entered in the first name field of the form-- that is, by looking inside the form object at the fName (first name) field, you can get the value of whatever has been entered into that field. As the visitor may have entered either an upper case or lower case name, we force the name to upper case by using the toUpperCase() method, and then store the result in the firstNm variable. We also do the same for the entry into the last name field, which is stored in lastNm.

firstNm = myForm.fName.value.toUpperCase() lastNm = myForm.lName.value.toUpperCase()

If the visitor entered any value as their first name, we want to set the firstNum variable. This is going to be used later as a reference into the firstName array, so it needs to be a number between 0 and 25, where A=0 and Z=25. We get the numeric value of the first character of the first name by passing the charCodeAt() method as 0, which means the first character in the string. This method returns the ASCII value of a character; the ASCII value of "A" is 65, "B" is 66, and all the way to "Z" is 90. So, subtracting 65 from this value will return what we want: a number between 0 and 25.

if (firstNm != "") { firstNum = firstNm.charCodeAt(0) - 65

Of course, this works if we assume that the visitor entered a valid first name. If they entered a number or a space in the field, for instance, we wouldn't have a valid result. So, we check to see if firstNum is between 0 and 25 before continuing on.

if (firstNum >= 0 && firstNum <= 25) {

We then check to see if a last name was entered. If so, we want to get the numeric value of the first and last characters of the last name. The only difference between this and the first name check done previously is the process used to check the last character of the last name. When we look at the characters in a string as zero-relative (starting at zero), they go from 0 to 1 less than its length. So, passing charCodeAt() a value of (lastNm.length-1) gives the ASCII value of the last character in the name.

if (lastNm != "") { lastNum1 = lastNm.charCodeAt(0) - 65 lastNum2 = lastNm.charCodeAt((lastNm.length-1)) - 65

If both last name values are between 0 and 25, everything was entered as it should have been. Now we're ready to do the actual name conversion and put the result into the variable sillyName. Your new name is found by concatenating your new first name (found by using firstNum as an index into the firstName array) together with a space, followed by the two halves of your new last name (which are calculated just like the first name).

if (lastNum1 >= 0 && lastNum1 <= 25 && lastNum2 >= 0 && lastNum2 <= 25) { sillyName = firstName[firstNum] + " " + lastName1[lastNum1] + lastName2[lastNum2]

Your new name is announced via an alert message, and the function then returns a value of false. This return value is a little trick to keep the form from trying to return to the server and run the action. If you return a value of false to an onSubmit handler, the form thinks that the form didn't validate, and so, cancels any further handling of the submit process.

alert("Your silly name is " + sillyName) return false

All that's left now are the two error routines. Each passes back the appropriate error: either the first or last name was entered incorrectly. The next step in both cases is to put the cursor into the offending field so that the user can more easily fix the problem. Next, if there actually was bad data entered in the field, we select the contents so that it can be typed over immediately. Finally, we return false, once again telling the onSubmit handler that its job is done.

alert("That's not a valid last name") myForm.lName.focus() myForm.lName.select() return false

So, while you have learned how to convert your name into something silly, you also learned a little about string handling, arrays, error checking, and form validation. Not too bad for a silly little script, eh?

Click here to see this code in action.

this article & script are based on ones that originally appeared in Ask the JavaScript Pro on DevX.com.


Dori Smith is co-author (with Tom Negrino) of JavaScript for the WWW: Visual QuickStart Guide, 5th edition and Mac OS X Unwired, author of Java 2 for the WWW: Visual QuickStart Guide, and numerous print and online magazine articles. She is a frequent speaker at industry conferences and is a member of the Web Standards Project Steering Committee. She maintains the Backup Brain weblog, and is also the List Mom for the Wise-Women mailing lists.