While I was working on a full Ajax interface based on pure ajax calls and not on any framework, I implemented some basic and simple methods that we use all the time in the server code, and just not exist in javascript. It's not big deal, but since I wrote them, I use them all the time.
Even it is very simple, I decided to share it here. Hope it will save other coders few minutes:
Cache object:
//
// Cach object implementation
//
var Cache = newfunction()
{
var _cache = new Array();
this.Insert = function ( key, value ){
_cache[key] = value;
}
this.Get = function ( key ){
return _cache[key];
}
this.Contains = function ( key ){
if( !_cache[key] || _cache[key] == null ) returnfalse;
elsereturntrue;
}
};
The use of the cache is as simple as it is in the server side, and it is realy useful to save some calls to the server:
Cache.Insert("myKey","MyValue");
if( Cache.Contains("myKey") ) alert( "Yeee the value of my key isin the cache:" + Cache.Get("myKey") );
String.Format(string,params) & String.IsNullOrEmpty(string) :
//
// String.Format implementation
//
String.Format = function(format,args){
var result = format;
for(var i = 1 ; i < arguments.length ; i++) {
result = result.replace(new RegExp( '\\{' + (i-1) + '\\}', 'g' ),arguments[i]);
}
return result;
}
//
// String.IsNullOrEmpty implementation
//
String.IsNullOrEmpty = function(value){
if(value){
if( typeof( value ) == 'string' ){
if( value.length > 0 )
returnfalse;
}
if( value != null )
returnfalse;
}
returntrue;
}
Again, the use is the same as server side:
alert( String.Format("Hello {0}. Yes, hello {0} again. My name is {1}","world","Miron") );
if( String.IsNullOrEmpty('') ) alert('Empty string');
StartsWith(string suffix,bool ignoreCase), EndsWith(string suffix,bool ignoreCase) and Trim() :
//
// string.StartWith implementation
//
String.prototype.StartsWith = function(prefix,ignoreCase) {
if( !prefix ) returnfalse;
if( prefix.length > this.length ) returnfalse;
if( ignoreCase ) {
if( ignoreCase == true ) {
return (this.substr(0, prefix.length).toUpperCase() == prefix.toUpperCase());
}
}
return (this.substr(0, prefix.length) === prefix);
}
//
// string.EndsWith implementation
//
String.prototype.EndsWith = function(suffix,ignoreCase) {
if( !suffix ) returnfalse;
if( suffix.length > this.length ) returnfalse;
if( ignoreCase ) {
if( ignoreCase == true ) {
return (this.substr(this.length - suffix.length).toUpperCase() == suffix.toUpperCase());
}
}
return (this.substr(this.length - suffix.length) === suffix);
}
//
// string.Trim implementation
//
String.prototype.Trim = function() {
returnthis.replace(/^\s+|\s+$/g, '');
}
The last three are working on an istance of a string:
var test = "Hello Words ";
test = test.Trim();
var end = test.EndsWith("ds",true);
var begin = test.BeginsWith("rr",false);
All the code can be downloaded here: