Sunday, February 21, 2010

Some JavaScript utility functions


/**
* Trim a string
*/
function trim(str) {
str = str + '';
return str.replace(/^\s+|\s+$/g, '');
}

/**
* Merge two JSONs, with controllable overwrite.
*/
function mergeJson(target, source, overwrite) {
for (var item in source) {
if (target[item] && typeof source[item] === 'object') {
this.mergeJson(target[item], source[item]);
} else if (!target[item] || overwrite === true) {
target[item] = source[item];
}
}
return target;
}

/**
* Check if an array contains a given elements.
*/
function arrayContainsElement(arr, ele) {
var contains = false;
if (arr) {
for (var i = 0; i < arr.length; i++) {
if (this.trim(arr[i]) === this.trim(ele)) {
contains = true;
break;
}
}
}
return contains;
}

No comments:

Post a Comment