Create reusable routines in JavaScript

Tired of rewriting everything? Here's how to build a component library for JavaScript and reuse common routines -- simply by cutting and pasting code

Professional programmers live by an old adage: "Write once, use many times." When you develop a scheme for doing something in JavaScript -- or almost any programming language, for that matter -- you should save your efforts for use the next time a similar problem crops up. You never know when you'll need that random number generator, array sorter, or whatever it is you've worked on for the last two weekends in a row.

JavaScript supports user-defined functions, which is highly advantageous for developing a library of reusable code. You can place code you think you might reuse into one or more functions and save those functions in a text file for future reference. Then, when you need one of the functions, you can copy and paste it into your JavaScript program. To call the function, you must also add a statement elsewhere in your JavaScript program.

When learning a new programming language, one of the first things you should do is create commonly used "plug-and-play" routines. If you're new to JavaScript, you might want to consider starting with a half-dozen or so simple routines that you think might be helpful. Even if you don't end up using them, you'll learn a lot about JavaScript in the process.

This column introduces the concept of creating these so-called plug-and-play routines that can be ported from one JavaScript program to another. It also demonstrates the concept of reusable routines by presenting a number of ready-to-go functions you can use in your own JavaScript programs. Note that the functions are not meant to be cure-alls; some could even be improved. Rather, they are presented as readily editable functions. You are free to enhance or modify any routine presented here and incorporate it into your own library.

Create and use "plug-and-play" routines

To create a reusable plug-and-play routine, simply enclose it within a function in a JavaScript program. After it has been fully debugged, you can copy the function to a library file that you keep on your computer's hard-disk drive. When you want to use the function, simply open the library file, copy it, and paste it into your current JavaScript project.

Recall that JavaScript is an interpreted language, and that unlike Java and other interpreted languages, it does not directly support a #include statement. With the #include statement you can define one or more library files that contain functions you want the main program to refer to. You will need to supply the actual function as part of your JavaScript program, either in the same HTML document that contains the JavaScript code, or in a .js file that contains the JavaScript for the document. (The .js file is used with Netscape Navigator 3.0 and later and is defined with the <SCRIPT SRC="filename.js"> construct. See the JavaScript documentation from Netscape for more information.)

Note that with either method, the browser must download the entire JavaScript program so that it can be executed. Stuffing the JavaScript code into a .js file does not save time or provide added security. And it is a bad idea to place all of your reusable routines in a .js file if you aren't using them in your program; unused routines waste bandwidth. It is far better to selectively copy and paste only those routines you use for each program you write.

How routines are like JavaScript functions

Most of the plug-and-play routines you write will be functions that return a value of some type. As such, they behave very much like JavaScript's built-in functions, such as eval, parseInt, or escape. I'll use the JavaScript parseInt function as an example. It takes a string and "parses" it to a numeric value. The parseInt function has many uses and syntaxes, but the most common goes like this:

var Ret = parseInt ("12345");

As shown here, the parseInt function takes one parameter, which is a number string value. When JavaScript executes this function, it converts the string value to a number ("12345" becomes 12345). Thus, the value can be used in mathematical expressions. The returned value is stored in a variable named Ret.

Note: As with built-in JavaScript functions that return a variable, you can often use user-defined functions in complex expressions. For example, JavaScript lets you use the parseInt function in the following manner, because it forms a complex expression using an if statement:

StringValue = "12";
if (parseInt(StringValue) < 10)

The parseInt function returns the numeric value of the StringValue variable ("12"), and this is used in an "if" expression. The expression tests whether the numeric value 12 is less than the number 10.

Now consider a user-defined function -- say one that returns the length of a string. (We'll use this as an example because it's quick and easy to demonstrate, not because it's particularly useful.) The function is defined as:

function stringLength(InString) {
    var Temp = InString.length;
    return (Temp);
}

To use this function you provide an instruction elsewhere in your JavaScript program that refers to the function by name and provides the required parameter. For example, the following code displays "14" in an alert box; it's the length, in characters, of the string "This is a test."

var Ret;
var MyString = "This is a test";
Ret = stringLength(MyString);
alert(Ret);

Passing parameters to functions

It is quite common to create functions that use one or more parameters. Parameters work the same way with your own plug-and-play routines as they do with JavaScript functions and object methods. If you plan to use any of the reusable routines presented in this column, be sure to provide all the parameters specified in the appropriate order, or an error will result.

Parameters passed to a function are contained within parentheses and follow the name of the routine. If more than one parameter is used with a routine, the parameters are separated by a comma, which is JavaScript's syntactical standard. In almost all cases, you can include the actual value of the parameter you want the routine to use, as in:

var Ret = leftTrim("   This is a test");

Alternatively, you can assign the value you want to use for the parameter to a variable, and stick the variable name inside the parentheses, as shown:

var StrVar = "   This is a test";
var Ret = leftTrim(StrVar);

As with JavaScript functions and object methods, the reusable functions in this column, and the ones you will write for yourself, usually expect certain kinds of values at each parameter. One parameter may be a string value, another a number, the third an array, and the fourth an object. Be sure always to use the right kind of data or an error is likely to result.

Starter library: Some plug-and-play functions you can use

During the past year of writing JavaScript programs, I've discovered that about 85 percent of my projects have involved commonly used code. I've developed an extensive library of this code, some of which is presented here. Feel free to snatch any or all of the functions demonstrated below. And of course you're free to improve upon these functions, and make them more efficient.

For the sake of simplicity, the actual code for each routine is not presented in the body of this column. Instead, it is part of the example provided with each routine. Click on the link for each example to see it demonstrated. You can view the code for the routine in Netscape Navigator by choosing the following menu items: "View," "Document Source."

Note: These routines were tested with Navigator versions 2.02 and 3.0 under Windows 95. JavaScript can and does exhibit unstable behavior when used on different browser platforms and versions. If you plan to use any of the following code in a public Web page, be sure to test it with as many JavaScript-capable browsers as you can. Such is the downside of using JavaScript.

allowBrowser

The allowBrowser function lets you quickly and easily determine whether the user's version of Navigator is allowed for your application. This is handy if you need to prevent a user from accessing parts of your page that may cause problems with a particular Netscape platform. You can identify which browsers you want to "allow" by using a letter. You can use the letters singly or in combination if you wish to allow multiple browsers.

Letter symbolNetscape platform
WWindows 9x (such as Windows 95)
wWindows 3.1
NWindows NT
MMac PPC
mMac 68K
XX Window

The syntax for allowBrowser is:

var Ret = allowBrowser (AllowString);

AllowString above is one or more characters that represent the browsers you wish to allow. The function returns Boolean true if the user's browser is among those listed in allowString; false if not.

This example displays true if you are using the Windows 9x version of Navigator; false for any other.

var Ret = allowBrowser("W");
alert (Ret);

Feel free to mix and match browsers if you wish to allow for a variety of them. Here are some examples:

Example function callAllows
allowBrowser("WwMm")Windows 3.1, Windows 9x, Mac PPC, Mac 68K
allowBrowser("XWN")X Window, Windows 9x, Windows NT
allowBrowser("wX")Windows 3.1, X Window

One of the main purposes of the allowBrowser function is to check the user's browser so that you can avoid any platform-specific bugs. But you can use it for other applications. For example, you can check for the Windows versions ("WwN"), and display a "Welcome Windows Users" message at the top of your page.

allowInString

The allowInString function tests every character in a string against a set of "allowed" characters. If the function finds a character that is not allowed, it returns false; otherwise it returns true. The allowInString function primarily is used for form or input validation. The syntax for the allowInString function is:

var ret = allowInString (InString, RefString);

InString is the string you want to test. RefString is the list of acceptable characters. The function returns Boolean true if InString does not contain any invalid characters; otherwise it returns false.

This example displays false: The input string contains invalid characters (the dollar sign is not allowed):

var TestThisString = ",987,239.28";
var ValidString = "01234567890.,";
var Ret = allowInString (TestThisString, ValidString);
alert (Ret);

allowNotInString

The allowNotInString function is the logical inverse of the allowInString function above. It tests every character in a string against a set of "disallowed" characters. If the function finds any character contained in the disallowed list, it returns false; otherwise it returns true. One of the primary uses of the allowNotInString function is for form or input validation. The syntax is:

var ret = allowNotInString (InString, RefString);

InString is the string you want to test. RefString is the list of unacceptable characters. The function returns Boolean true if InString does not contain any invalid characters; otherwise it returns false.

This example displays true: The input string does not contain any invalid characters. The example tests whether a CompuServe ID number contains 8, 9, or a comma, which is not allowed (the comma is allowed within CompuServe, but not when specifying a CompuServe address through the Internet).

var TestThisString = "71333.1776";
var ValidString = "89,";
var Ret = allowNotInString (TestThisString, ValidString);
alert (Ret);

filenameOnly

The filenameOnly function returns just the filename (minus the path) of a fully qualified URL. The syntax of the filenameOnly function is:

var Ret = filenameOnly(InString);

InString is the fully qualified URL you want to use, such as:

http://mydomain.com/dir/homepage.html 

The function returns "homepage.html." If you wish to return the filename of the current document, use location.href for InString. The function returns the filename only of the fully qualified URL.

This example returns the filename only of the current document.

var Ret = filenameOnly(location.href);
alert(Ret);

isAlphabeticString

The isAlphabeticString function determines if all the characters in a string are alphabetic characters (not numbers or punctuation). Here is the syntax for the isAlphabeticString function:

var Ret = isAlphabeticString (TestString)

TestString is the string you want to test. The function returns a numeric value: 1 if the string is all-alphabetic; 0 if it is not.

This example displays a specific message telling you the result of the text you typed.

var Ret = prompt ("Type some characters ");
if (isAlphabeticString(Ret))
    alert ("All characters were alphabetic");
else
    alert ("At least one character was not alphabetic");

isNumberString

The isNumberString function determines if all the characters in a string are numbers. The syntax is:

var Ret = isNumberString (TestString);

TestString is the string you want to test. The function returns a numeric value: 1 if the string is all numbers; 0 if it is not.

This example displays a specific message telling you the result of the text you typed.

var Ret = prompt ("Type some numbers");
if (isNumberString(Ret))
    alert ("All characters are numbers ");
else
    alert ("At least one character is not a number");

isWithinRange

The isWithinRange function tests if a string's numeric value is within a certain range. The function uses a string input because this is the likely data type, such as that used with form text boxes or the response to a prompt box. You can specify the lower allowed range and the upper allowed range. The syntax for the isWithinRange function is:

var Ret = isWithinRange(InString, RangeMin, RangeMax);
1 2 Page 1
Page 1 of 2