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

1 2 Page 2
Page 2 of 2
  • 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.

Learn more about this topic

This story, "Create reusable routines in JavaScript" was originally published by JavaWorld.

Copyright © 1997 IDG Communications, Inc.

1 2 Page 2
Page 2 of 2