Javascript Custom Functions Part 2

addSpace

Add space to the beginning of an argument.

Syntax

addSpace(stringValue, [numlength])

stringValue is the string which you want to add the space to. numlenght is the length of the return string, i.e. add space/s to the string to make it "numlength" long. Default "numlength" is 10.

Description

When you want to align the value of the form text box, you can use this function.

Examples

The following returns "    123.45".
addSpace("123.45", 10);
addSpace("123.45");

Code

function addSpace(argvalue, numlength) { if (! numlength > 0) numlength = 10; if (argvalue.length < numlength) { for(var i = argvalue.length; i < numlength; i++) argvalue = " " + argvalue; } return argvalue; }

customSplit

Split the argument string into an array of strings.

Syntax

customSplit(strValue, separator, strArrayName)

strValue is the string to be splited with separator as the delimeter. After spliting, array of strings are stored in new "Array" object, strArrayName.

Description

Since some of the browsers does not support latest version of javascript, which has split() function. "customSplit" function can be used then.

This function will return the length of the array created.

Examples

var strvalue = "abc##123##zzz##$$$";
var returnArraySize = customSplit(strvalue, "##", "NewArray");
The above will create the following:
NewArray[0] has value "abc"
NewArray[1] has value "123"
NewArray[2] has value "zzz"
NewArray[3] has value "$$$"
returnArraySize      has value "4"

Code

function customSplit(strvalue, separator, arrayName) { var n = 0; if (separator.length != 0) { while (strvalue.indexOf(separator) != -1) { eval("arr"+n+" = strvalue.substring(0, strvalue.indexOf(separator));"); strvalue = strvalue.substring(strvalue.indexOf(separator)+separator.length, strvalue.length+1); n++; } eval("arr" + n + " = strvalue;"); arraySize = n+1; } else { for (var x = 0; x < strvalue.length; x++) { eval("arr"+n+" = \"" + strvalue.substring(x, x+1) + "\";"); n++; } arraySize = n; } eval(arrayName + " = new makeArray(arraySize);"); for (var i = 0; i < arraySize; i++) eval(arrayName + "[" + i + "] = arr" + i + ";"); return arraySize; }

DeleteCookie function

Delete the cookie.

Syntax

DeleteCookie(cookieName)

cookieName is the cookie that you want to delete.

Description

Examples

Code

function DeleteCookie(cookiename) { var exp = new Date(); exp.setTime(exp.getTime() - 1); var cookieVal = getCookie(cookiename); if (cookieVal != null) document.cookie = name + "=" + cookieVal + "; expires=" + exp.toGMTString(); return; }

See also

getCookie functions.

formatDecimal function

Print the floating point number with certain decimal point.

Syntax

formatDecimal(number, boolean, decimal)

number is the floating point number which will be formatted.

boolean is used to decide whether add "0" at the end of the floating point number or not.

decimal is how many decimal point you wnat. (Default is 2)

Description

This function will print the floating point number passed in with the decimal point that users need.

Examples

formatDecimal("123.2333", true, 2); will return "123.23".
formatDecimal("123", true, 2);  will return "123.00".
formatDecimal("123", false, 2);  will return "123".
formatDecimal("123.2", true, 2); will return "123.20".
formatDecimal("123.2", false, 2); will return "123.2".
formatDecimal("123.456", true, 2); will return "123.46".
formatDecimal(".235", true, 2);  will return "0.24".
formatDecimal("0.9999", true, 2); will return "1.00".
formatDecimal("0.9999", false, 2); will return "1".


Code

function formatDecimal(argvalue, addzero, decimaln) { var numOfDecimal = (decimaln == null) ? 2 : decimaln; var number = 1; number = Math.pow(10, numOfDecimal); argvalue = Math.round(parseFloat(argvalue) * number) / number; // If you're using IE3.x, you will get error with the following line. // argvalue = argvalue.toString(); // It works fine in IE4. argvalue = "" + argvalue; if (argvalue.indexOf(".") == 0) argvalue = "0" + argvalue; if (addzero == true) { if (argvalue.indexOf(".") == -1) argvalue = argvalue + "."; while ((argvalue.indexOf(".") + 1) > (argvalue.length - numOfDecimal)) argvalue = argvalue + "0"; } return argvalue; }

See also

formatCurrency function.

formatValue function

Print a number according to the format specified. Used for currency format.

Syntax

formatValue(argvalue, format)

argvalue is the number which will be formatted.

format is the format of the result.

Description

The number passed in will be formatted according to the format specified by the user. This function is written for formatting a currency number.

And formatDecimal function is needed.

Examples

formatValue(1223.434, "$##,###.##")  will return "$1,223.43"
formatValue(1223.43, "$##,###.##")  will return "$1,223.43"
formatValue(1223., "$##,###.##")  will return "$1,223.00"
formatValue(1223, "$##,###.##")  will return "$1,223.00"
formatValue(23., "$##,###.##")   will return "$23.00"
formatValue(23.3, "$##,###.##")  will return "$23.30"
formatValue(124343423.3, "$###,###,###.##") will return "$124,343,423.30"

Code

function formatValue(argvalue, format) { var numOfDecimal = 0; if (format.indexOf(".") != -1) { numOfDecimal = format.substring(format.indexOf(".") + 1, format.length).length; } argvalue = formatDecimal(argvalue, true, numOfDecimal); argvalueBeforeDot = argvalue.substring(0, argvalue.indexOf(".")); retValue = argvalue.substring(argvalue.indexOf("."), argvalue.length); strBeforeDot = format.substring(0, format.indexOf(".")); for (var n = strBeforeDot.length - 1; n >= 0; n--) { oneformatchar = strBeforeDot.substring(n, n + 1); if (oneformatchar == "#") { if (argvalueBeforeDot.length > 0) { argvalueonechar = argvalueBeforeDot.substring(argvalueBeforeDot.length - 1, argvalueBeforeDot.length); retValue = argvalueonechar + retValue; argvalueBeforeDot = argvalueBeforeDot.substring(0, argvalueBeforeDot.length - 1); } } else { if (argvalueBeforeDot.length > 0 || n == 0) retValue = oneformatchar + retValue; } } return retValue; }

See also

formatDecimal function.

GetCookie function

Get the value of a cookie.

Syntax

GetCookie(CookieName)

CookieName is the cookie whose value that you want to get.

Description

If the cookie specified doesn't exist, "null" will be returned.

Examples

If the document.cookie contains:
USER_ID=abc
USER_GP=

// variable "userid" has value "abc".
var userid = GetCookie("USER_ID");
// variable "usergp" has value "".
var usergp = GetCookie("USER_GP");
// variable "userpw" has null value.
var userpw = GetCookie("USER_PW");

Code

function GetCookie(name) { var arg = name + "="; var alen = arg.length; var clen = document.cookie.length; var i = 0; while (i < clen) { var j = i + alen; if (document.cookie.substring(i, j) == arg) return GetCookieVal(j); i = document.cookie.indexOf(" ", i) + 1; if (i == 0) break; } return null; } function GetCookieVal(offset) { var endstr = document.cookie.indexOf(";", offset); if (("" + endstr) == "" || endstr == -1) endstr = document.cookie.length; return unescape(document.cookie.substring(offset, endstr)); }

isEmail function

Determine an argument if it is an email address format.

Syntax

isEmail(testValue)

testValue is the value that you want to check.

Description

This function only check if the argument has email address's format, i.e. id@some.host, it will not connect to some.host to check if it is valid. There is not any method to validate an email address except you ask the user to key in their correct email address.

It is better you use trim to remove both the leading and the trailing space/s before you pass the value to this function.

Examples

The following return "true".
isEmail("abc@some.host");

The followings return "false".
isEmail("abc");
isEmail("abc@somehost");
isEmail("abc@.some.host");
isEmail("abc@some.host.");

Code

function isEmail(argvalue) { if (argvalue.indexOf(" ") != -1) return false; else if (argvalue.indexOf("@") == -1) return false; else if (argvalue.indexOf("@") == 0) return false; else if (argvalue.indexOf("@") == (argvalue.length-1)) return false; // arrayString = argvalue.split("@"); (works only in netscape3 and above.) var retSize = customSplit(argvalue, "@", "arrayString"); if (arrayString[1].indexOf(".") == -1) return false; else if (arrayString[1].indexOf(".") == 0) return false; else if (arrayString[1].charAt(arrayString[1].length-1) == ".") { return false; } return true; }

isURL function

Determine an argument if it is a URL.

Syntax

isURL(testValue)

testValue is the value that you want to check.

Description

Examples

The followings will return "true".
isURL("http://some.host");
isURL("http://some.host/");
isURL("http://some.host/dir");
isURL("http://some.host/dir/");
isURL("http://some.host/dir/htmlfile");
isURL("http://some.host:123");
isURL("http://some.host:123/");

The followings will return "false".
isURL("http://.some.host/");
isURL("http://some.host./");
isURL("http://some.host:/");
isURL("http://some.host:.123/");
isURL("http://some.host:123./");
isURL("http://some.host:123./dir";
isURL("http://");
isURL("htp://");

Code

function isURL(argvalue) { if (argvalue.indexOf(" ") != -1) return false; else if (argvalue.indexOf("http://") == -1) return false; else if (argvalue == "http://") return false; else if (argvalue.indexOf("http://") > 0) return false; argvalue = argvalue.substring(7, argvalue.length); if (argvalue.indexOf(".") == -1) return false; else if (argvalue.indexOf(".") == 0) return false; else if (argvalue.charAt(argvalue.length - 1) == ".") return false; if (argvalue.indexOf("/") != -1) { argvalue = argvalue.substring(0, argvalue.indexOf("/")); if (argvalue.charAt(argvalue.length - 1) == ".") return false; } if (argvalue.indexOf(":") != -1) { if (argvalue.indexOf(":") == (argvalue.length - 1)) return false; else if (argvalue.charAt(argvalue.indexOf(":") + 1) == ".") return false; argvalue = argvalue.substring(0, argvalue.indexOf(":")); if (argvalue.charAt(argvalue.length - 1) == ".") return false; } return true; }

isW function

Determine an argument if it only contains "word" characters.

Syntax

isW(testValue)

testValue is the value that you want to check.

Description

"Word" characters are alphanumeric plus "_".

Example

The followings will return "true".
isW("abc123")
isW("ABC123")
isW("aBc_123")

The followings will return "false".
isW("abc 123")
isW("@#+=")
isW("! Abc")

Code

function isW(argvalue) { var onechar = ""; for (var n = 0; n < argvalue.length; n++) { onechar = argvalue.substring(n, n+1); if ((onechar < "0" || onechar > "9") && (onechar < "A" || onechar > "Z") && (onechar < "a" || onechar > "z") && (onechar != "_")) { return false; } } return true; }

ltrim function

Remove the leading space/s of an argument.

Syntax

ltrim(stringValue)

stringValue is the string which the leading space/s will be removed.

Description

Examples

The following will return "abc ".
ltrim("  abc ")
The following will return "a b c  ".
ltrim("  a b c  ")

Code

function ltrim(argvalue) { while (1) { if (argvalue.substring(0, 1) != " ") break; argvalue = argvalue.substring(1, argvalue.length); } return argvalue; }

makeArray function

Create an array object.

Syntax

makeArray(intArraySize)

intArraySize is the length of the array created.

Description

Some browser does not support latest javascript which has Array object. This function can be used in those browser.

Examples

The following will create an array with 3 in length.
newArray = new makeArray(3);

Code

function makeArray(IntarrSize) { for (var n = 0; n < IntarrSize; n++) this[n] = ""; return this; }

numCheck function

Determine an argument if it only contains number.

Syntax

numCheck(testValue)

testValue is the value that you want to check.

Description

numCheck function will return true if the argument only contains "0-9".

Examples

The followings will return "true".
numCheck("1234")
numCheck("0123")

The followings will return "false".
numCheck("abcd")
numCheck("a123")
numCheck("123a")
numCheck("12.3")

Code

function numCheck(argvalue) { if (argvalue.length == 0) return false; for (var n = 0; n < argvalue.length; n++) if (argvalue.substring(n, n+1) < "0" || argvalue.substring(n, n+1) > "9") return false; return true; }

ParseCookies function

Parse the cookies data and assign these data to "document.Cookie_cookie_name".

Syntax

ParseCookies()

Description

The value of cookie, cookieName, is stored in "document.Cookie_cookieName.value".

There are few ways to save the cookie data, but I found that this is the way which works in both Netscape3.0 and Internet Explorer3.0.

Examples

If the server returns the following cookie:
 Set-Cookie: Cookie1=Value1; Cookie2=Value2
After you call the ParseCookies().
parseCookies();
"document.Cookie_Cookie1.value" will contains value "Value1";
"document.Cookie_Cookie1.name" will contains value "Cookie1";
"document.Cookie_Cookie2.value" will contains value "Value2";
"document.Cookie_Cookie2.name" will contains value "Cookie2";

Code

function ParseCookies() { var cookie_string; var cookie_name; var cookie_value; var tmpcookie = document.cookie; var cookie_count = 0; while (tmpcookie.indexOf("; ") != -1) { cookie_string = tmpcookie.substring(0, tmpcookie.indexOf("; ")); cookie_name = cookie_string.substring(0, cookie_string.indexOf("=")); cookie_value = cookie_string.substring(cookie_string.indexOf("=") + "=".length, cookie_string.length); eval("document.Cookie_" + cookie_name + " = new Cookies(cookie_name, cookie_value);"); tmpcookie = tmpcookie.substring(tmpcookie.indexOf("; ") + "; ".length, tmpcookie.length); cookie_count++; } cookie_name = tmpcookie.substring(0, tmpcookie.indexOf("=")); cookie_value = tmpcookie.substring(tmpcookie.indexOf("=") + "=".length, tmpcookie.length); eval("document.Cookie_" + cookie_name + " = new Cookies(cookie_name, cookie_value);"); cookie_count++; return cookie_count; } function Cookies(argname, argvalue) { this.name = argname; this.value = unescape(argvalue); return this; }

replace function

Substitute a string X to a string Y in an argument.

Syntax

replace(stringValue, X, Y)

stringValue is the string which has all X will be substituted by Y.

Description

This function will replace all the string X to string Y in the argument, it can not change the string X in certain place.

Examples

The following will return "abcABCdefgh".
replace("abc123defgh", "123", "ABC");

Code

function replace(argvalue, x, y) { if ((x == y) || (parseInt(y.indexOf(x)) > -1)) { errmessage = "replace function error: \n"; errmessage += "Second argument and third argument could be the same "; errmessage += "or third argument contains second argument.\n"; errmessage += "This will create an infinite loop as it's replaced globally."; alert(errmessage); return false; } while (argvalue.indexOf(x) != -1) { var leading = argvalue.substring(0, argvalue.indexOf(x)); var trailing = argvalue.substring(argvalue.indexOf(x) + x.length, argvalue.length); argvalue = leading + y + trailing; } return argvalue; }

rtrim function

Remove the trailing space/s of an argument.

Syntax

rtrim(stringValue)

stringValue is the string that you want to remove its trailing space/s.

Description

Examples

The following will return "abc".
rtrim("abc   ")
The following will return "a b c".
rtrim("a b c   ")
The following will return "  abc".
rtrim("  abc  ")

Code

function rtrim(argvalue) { while (1) { if (argvalue.substring(argvalue.length - 1, argvalue.length) != " ") break; argvalue = argvalue.substring(0, argvalue.length - 1); } return argvalue; }

SetCookie function

Setting new cookie value.

Syntax

SetCookie(cookiename, cookievalue, expires, path, domain, secure)

Description

To retrieve the cookie's value, try parseCookie function.

For more information about cookie, see Netscape's Cookie Specification at http://home.netscape.com/newsref/std/cookie_spec.html.

Examples

SetCookie("Cookie1", "Value1", null, "/");
SetCookie("Cookie2", "Value2", new Date(), "/");
document.cookie will have value "Cookie1=Value1; Cookie2=Value2".

Code

function SetCookie(cookiename, cookievalue) { var argv = SetCookie.arguments; var argc = SetCookie.arguments.length; var expires = (argc > 2) ? argv[2] : null; var path = (argc > 3) ? argv[3] : null; var domain = (argc > 4) ? argv[4] : null; var secure = (argc > 5) ? argv[5] : false; document.cookie = cookiename + "=" + escape(cookievalue) + ((expires == null) ? "" : ("; expires=" + expires.toGMTString())) + ((path == null) ? "" : ("; path=" + path )) + ((domain == null) ? "" : ("; domain=" + domain )) + ((secure == true) ? "; secure" : ""); return; }

trim function

Remove both the leading and the trailing space/s of an argument.

Syntax

trim(stringValue)

stringValue is the string which the leading and the trailing space/s will be removed.

Description

When you use this function, make sure ltrim and rtrim are inside the same html file too.

Examples

The following will return "abc".
trim("  abc  ")
The following will return "a b c".
trim("  a b c  ")

Code

function trim(argvalue) { var tmpstr = ltrim(argvalue); return rtrim(tmpstr); }

0 Responses to "Javascript Custom Functions Part 2"