Pages

Wednesday, March 31, 2010

Native Javascript String Class Enhancements

This post consist of a cluster of functions that are used to extend the usage of Javascript String Object with custom functions which are added to the native String object's prototype

The native Javascript String Object will be enhanced with the following properties if the scripts in this post are included into your application.

  • strLeft 
  • strLeftBack
  • strRight
  • strRightBack
  • replaceAll
  • toProperCase

/*
 *   @Created :  31st Mar 2010
 *   @Author  :  Karthikeyan A
 *   @Purpose : To mimic the functions @left and StrLeft in formula
 *                    and Lotusscript respectively
 */


String.prototype.strLeft=function(seperator)    {
    var pos=this.indexOf(seperator);
    var result=this.substring(0,pos)
    return result;
}


/*
 *   @Created :  31st Mar 2010
 *   @Author  :  Karthikeyan A
 *   @Purpose : To mimic the functions @leftBack and StrLeftBack in
 *                    formula and Lotusscript respectively
 */


String.prototype.strLeftBack=function(seperator)    {
    var pos=this.lastIndexOf(seperator);
    var result=this.substring(0,pos)
    return result;
}


/*
 *   @Created :  31st Mar 2010
 *   @Author  :  Karthikeyan A
 *   @Purpose : To mimic the functions @right and StrRight in formula
 *                    and Lotusscript respectively
 */


String.prototype.strRight=function(seperator)    {
    var pos=this.indexOf(seperator);
    var result=this.substring(pos+1,this.length)
    return result;
}


/*
 *   @Created :  31st Mar 2010
 *   @Author  :  Karthikeyan A
 *   @Purpose : To mimic the functions @RightBack and StrRightBack in  
 *                      formula and Lotusscript respectively
 */


String.prototype.strRightBack=function(seperator)    {
    var pos=this.lastIndexOf(seperator);
    var result=this.substring(pos+1,this.length)
    return result;
}

/*
 *   @Created :  1st Apr 2010
 *   @Author  :  Karthikeyan A
 *   @Purpose :  To replace all occurences of a substring in a string  
 *                    with an other string
 */

String.prototype.replaceAll = function(stringToFind,stringToReplace){
    var temp = this;
    var index = temp.indexOf(stringToFind);
        while(index != -1){
            temp = temp.replace(stringToFind,stringToReplace);
            index = temp.indexOf(stringToFind);
        }
    return temp;
 }

/*
 *    @Source: http://www.codeproject.com/KB/scripting/propercase.aspx
 */
String.prototype.toProperCase = function()    {
  return this.toLowerCase().replace(/^(.)|\s(.)/g,
      function($1) { return $1.toUpperCase(); });
}

No comments:

Post a Comment