Monday, November 16, 2009

Common JavaScript Functions

1. How to check is null or empty in javascript?
Answer:

function IsNullOrEmpty(inputValue){
if(typeof(inputValue)=="undefined") {
return false;
} else if(inputValue == '' || inputValue == ' ' || inputValue == null ) {
return false;
} else if(inputValue.length == 0) {
return false;
}
return true;
}

2. How to make a string builder class in javascript and use them?

Answer:


function StringBuilder(value)
{
this.strings = new Array("");
this.append(value);
}

// Appends the given value to the end of this instance.

StringBuilder.prototype.append = function (value)
{
if (value)
{
this.strings.push(value);
}
}

// Clears the string buffer

StringBuilder.prototype.clear = function ()
{
this.strings.length = 1;
}

// Converts this instance to a String.

StringBuilder.prototype.toString = function ()
{
return this.strings.join("");
}

Example :
// Create a StringBuilder class instance
var html = new StringBuilder();
html.append("
My Div
");
html.append("
My Div2
");
html.append("
My Div3
");
var textValue = html.toString();

3.How to check the enetered number is numeric or not?
Answer:

function isNumeric(value)
{
for(i=0;i {
//check numbers between the 0 to 9
if(!((value.charCodeAt(i)>=48) && (value.charCodeAt(i)<=57)))
{
return false
}
}
return true;
}

4. How to read the cookies?
Answer:
function ReadCookie(cookieName) {
var theCookie = "" + document.cookie;
var ind = theCookie.indexOf(cookieName);
if (ind == -1 || cookieName == "") return "";
var ind1 = theCookie.indexOf(';', ind);
if (ind1 == -1) ind1 = theCookie.length;
return unescape(theCookie.substring(ind + cookieName.length + 1, ind1));
}
5. How to replace the query string values?

Answer:
function replaceQueryString(url, param, value) {
var re = new RegExp("([?|&])" + param + "=.*?(&|$)", "i");
if (url.match(re))
return url.replace(re, '$1' + param + "=" + value + '$2');
else
return url + '&' + param + "=" + value;
}

No comments:

Post a Comment