Introduction
Recently, I have been doing a great deal of web development. Because of which, I decided to create an API
set for the more commonly used functions I routinely needed to implement in JavaScript. This article contains
two functions from my API set that may be of interest to web developers at large.
These functions wrap the process of adding, removing, and replacing items in a list -- a string with delimited
indexes using a special character. Here are just a couple of instances where you might want to use these functions...
If you must, for some reason, use JavaScript 1.0 this can be a lifesaver because arrays didn't exist in that
version. If you wish to work with multiple values in a single cookie, this will also prove to be severely useful (at least it does for me).
The two functions involved here are SetInList() and GetInList(). As you might
imagine, SetInList() will either insert or replace an index in a list and GetInList()
retrieve an index from a list.
SetInList() takes five parameters:
list = string containing the actual list
item = the value to place in the list
index = the index to be set
delim = the delimiter used to create the list
insert = whether or not to insert or replace the item (boolean)
GetInList() takes three parameters:
list = string containing the actual list
index = the index to be set
delim = the delimiter used to create the list
NOTE: The indexes are intended to be zero-based, and if the index cannot not be found in the list both functions will return false.
Example...
<script language="JavaScript" src="list.js"></script>
<script language="JavaScript"><!--
var list = "apples,oranges,pineapples,bannanas,peaches";
document.writeln("1 = \"" + list + "\"<br>");
list = SetInList(list, "grapes", 2, ",", true);
document.writeln("2 = \"" + list + "\"<br>");
list = SetInList(list, "tangerines", 4, ",", false);
document.writeln("3 = \"" + list + "\"<br>");
document.writeln("4 = \"" + GetInList(list, 3, ",") + "\"");
Will produce the output...
1 = "apples,oranges,pineapples,bannanas,peaches"
2 = "apples,oranges,grapes,pineapples,bannanas,peaches"
3 = "apples,oranges,grapes,pineapples,tangerines,peaches"
4 = "pineapples"