by Gordon Mccomb

Create reusable routines in JavaScript

how-to
Feb 1, 199718 mins

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

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);
  • InString is the string you want to test.
  • RangeMin is the minimum value to accept
  • RangeMax is the maximum value to accept.

The function returns Boolean true if the value falls within the range specified; otherwise it returns false.

This example redisplays the prompt box until the user clicks โ€œCancelโ€ or enters a value within the specified range. (This example doesnโ€™t test for non-numeric values. You will want to use the isNumberString function if you wish to test for non-numeric entry.)

var Ret;
var CtrlLoop = false;
while (!CtrlLoop) {
    Ret = prompt ("Type a number between 1 and 10", "");
    if (Ret == null)
        CtrlLoop = true;     // special handler for cancel 
    else
        CtrlLoop = isWithinRange (Ret, 1, 10);
}

mask

The mask function checks a string against an โ€œinput mask.โ€ The input mask is used to determine what types of characters are permitted for any part of the string. You can use the mask routine, for example, to ensure that users enter a telephone number in the format:

(xxx) xxx-xxxx

where the xs are only numbers, and the parentheses, space, and hyphen are required. The syntax for the function is:

var Ret = mask (InString, Mask);

InString is the string you want to test. Mask is the mask string. The Mask string uses special symbols to determine which characters should be used.

Mask CharacterMeaning
#Character at this position must be a number
?Character at this position must be an alphabetic character
!Character at this position must be number or alphabetic character
*Character at this position can be anything

Following are some examples:

MaskExample Matching String
###123
#?#1A2
#!?12A

The mask function returns a numeric value: 1 if the input string matches the mask; 0 otherwise. If you import the Mask routine to your own script, be sure also to import the following routines, also included in the example:

  • isNumberChar
  • isNumOrChar
  • isAlphabeticChar

This example tests a phone number in the form of (xxx) xxx-xxxx against a predefined mask. The result is 1; the number matches the pattern of the mask.

var Ret = Mask ("(800) 555-1212", "(###) ###-####");
alert (Ret);

Parser

The Parser function โ€œparses,โ€ or breaks apart, a string into its component parts, and is meant to be used in Navigator 2.0x, which lacks the split function found in Navigator 3.0 and later. The component parts are marked by a special parsing character, which can be user-defined (common parsing characters are ~ and ;). The parsed string is returned in a variable array; each element of the array contains a segment of the parsed string.

For example, suppose the input string is One;Two;Three;Four. After being processed, the variable array contains the following separate elements: One, Two, Three, and Four. The parser routine is helpful whenever you want to break up a larger string. The syntax for the parser routine is:

var Ret = parser(ParseStr, Sep)

ParseStr is the string you want to parse (the original string). Sep is the parsing character, such as โ€œ~โ€ or โ€œ;.โ€ (The parsing separator can be any single character, but obviously it should not be a character that will be found in the string itself.) The parser function returns the filled-out array. Use the element 0 to determine the number of elements in the array, such as Ret[0].

This example parses the test string into five elements, then prints out the elements on separate lines.

var ParseStr = "one;two;three;four;five"
var Sep=";";
var MyArray = parser(ParseStr, Sep)
var Temp = "";
for (Count=1; Count <=MyArray.length; Count++) {
    Temp += MyArray[Count] + "n";
}
alert(Temp);

pathOnly

The pathOnly function returns only the path (minus the filename) of a fully qualified URL. When you need to determine only the path of the current document, pathOnly can be used. The syntax for this function is:

var Ret = pathOnly(InString);

InString is the fully qualified URL you want to use. Following is an example:

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

The pathOnly function returns http://mydomain.com/dir/. If you wish to return the path of the current document, use location.href for InString. The function returns the path only (including host, port, domain, and so on) of the fully qualified URL.

This example returns only the path of the current document.

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

roundDollar

The roundDollar function โ€œcorrectsโ€ for JavaScriptโ€™s occasional overcompensation when using floating-point values. (This occurs with Navigator 2.0x but is not generally a problem with Netscape 3.0x and later.) For example, on many platforms a numeric value such as 8.87 becomes something like 8.8699999999999992. This is caused by overcompensation in the floating-point number calculation. The effects vary depending on the platform, as each computer type uses a different method of calculating and storing floating-point values.

The roundDollar function lops off the extra digits, and, if necessary, corrects the value. The value 8.87 is reconverted back to 8.87. The function can be used for any value with two digits to the right of the decimal point.

Note that in rounding, the value becomes a string, so it is no longer possible to perform math calculations on it. As an example, if the value is 8.87, and you add 1 to it, the result is 8.871, not 9.87. You should perform all math calculations before using the roundDollar function.

The syntax for the roundDollar function is:

var Ret = roundDollar (Val);

Val is the floating-point number you want to round. Only the two left fractional digits are returned; therefore 8.876 comes back rounded as 8.88. The function returns the rounded value in string form (no rounding error will occur with the value from this point on).

This example returns the correctly rounded string โ€œ8.87,โ€ even though on many platforms JavaScript overcompensates and stores the value as 8.8699999999999992.

value = 8.87;
alert ("Unrounded value: " + value);
Ret = roundDollar (value);
alert ("Rounded value: " + Ret);

stripCharString

The stripCharString function is used to strip two or more characters from a string. Its primary use is for formatting strings such as โ€œ,234.56โ€ to plain digits โ€” 123456. However, you can use it any time you need to remove a series of unwanted characters from a string. The syntax for the function is:

var Ret = stripCharString(InString, CharString);

InString is the string you want to process. Char represents the characters you want to strip. The function returns the stripped string.

This example strips the string โ€ ,2460.90 โ€ (note the spaces), and displays the result.

Ret = stripCharString (" ,2560.90 ", "$,. ");
alert (Ret);

testForLength

Use the testForLength function to test for various string-length conditions. You can test if a string is equal to a given length, less than or equal to a given length, and greater than or equal to a given length. The function primarily is used for validating input provided in a text box or prompt box. The syntax for the testForLength function is:

var Ret = testForLength (InString, EqualLength, LTELength, GTELength)
  • InString is the string to test.
  • EqualLength is the absolute length for the string (or -1 if using another parameter)
  • LTELength stands for less-than-or-equal to, and represents the maximum length allowed for the string (or -1 if using another parameter)
  • GTELength stands for greater-than-or-equal to, and represents the minimum length allowed for the string (or -1 if using another parameter)

The function returns Boolean true if the test string matches the length criteria; otherwise a false is returned.

This example tests if the input string (via a prompt box) is exactly 10 characters.

var TestString = prompt ("Type ten characters only", "")
if (TestString != null) {
    var Ret = testForLength (TestString, 10, -1, -1);
    alert (Ret);
}

Use the GTELength or LTELength parameters to test for greater than/equal to, and lesser than/equal to. Here are some examples:

ExampleTests For
testForLength (TestString, -1, 5, -1)Maximum string length is 5
testForLength (TestString, -1, -1, 7)Minimum string length is 7

Conclusion

A library or reusable code is one of the best ways to save some time and energy in writing JavaScript programs. Once you perfect a routine, you can store it in the library and use it whenever you need it. Instead of spending hours reinventing the wheel each time you write a JavaScript program, you can whip up a JavaScript solution to a problem in no time flat with your own plug-and-play routines.

Gordon McComb is an author, consultant, and lecturer. He has written 50 books and over a thousand magazine articles during his 20 years as a professional writer. More than a million copies of his books are in print. Gordon also writes a weekly syndicated newspaper column on computers, reaching several million readers worldwide. Gordonโ€™s latest book is The JavaScript Sourcebook, available from Wiley Computer Publishing.