Useful JavaScript Prototypes and methods

Here are some useful JavaScript prototypes and methods for various datatypes to extend your application functionalities:

  1. String

    • Proper Case (Convert string to Proper/Title Case)
      // convert string to proper case
      String.prototype.toProperCase = function () {
          return this.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
      };
      

      Usage:

      'your name'.toProperCase();
      Output: 'Your Name'
    • Snake Case (Convert studly case ‘YourName’ to ‘your_name’)
      // convert string to snake case
      String.prototype.toSnakeCase = function () {
          return this.replace(/(.)([A-Z])/g, "$1_$2").toLowerCase();
      };

      Usage:

      'YourName'.toSnakeCase();
      Output: 'your_name'
    • Is Date (Check if string is a Date)
      // check if string is a valid date
      String.prototype.isDate = function () {
          var dateFormat;
      
          if (toString.call(this) === '[object Date]') {
              return true;
          }
          if (typeof this.replace === 'function') {
              this.replace(/^\s+|\s+$/gm, '');
          }
      
          dateFormat = /(^\d{1,4}[\.|\\/|-]\d{1,2}[\.|\\/|-]\d{1,4})(\s*(?:0?[1-9]:[0-5]|1(?=[012])\d:[0-5])\d\s*[ap]m)?$/;
      
          if (dateFormat.test(this)) {
              return !!new Date(this).getTime();
          }
      
          return false;
      };

      Usage:

      '12-03-1990'.isDate();
      Output: true
    • Is Time (Check if string is a Time)
      // check if string is a time
      String.prototype.isTime = function () {
          var isValid = /^([0-1]?[0-9]|2[0-3]):([0-5][0-9])(:[0-5][0-9])?$/.test(this);
          return isValid;
      };

      Usage:

      '14:36'.isTime();
      Output: true
    • Is DateTime (Check if string is DateTime, to make it working, copy the above Date & Time Prototype)
      // check if string is a time
      String.prototype.isDateTime = function () {
          var date = this.split(" ");
      
          if (date[0].isDate() && date[1].isTime()) {
              return true;
          }
      
          return false;
      };

      Usage:

      '20-10-1990 14:36'.isDateTime();
      Output: true
  2. Date (Get Long and Short Month Names with Multilingual Support)

    • Month Long Name
      // getting month long name from Date object
      Date.prototype.getMonthName = function(lang) {
          lang = lang && (lang in Date.locale) ? lang : 'en';
          return Date.locale[lang].month_names[this.getMonth()];
      };
    • Month Short Name
      // getting month short name from Date object
      Date.prototype.getMonthNameShort = function(lang) {
          lang = lang && (lang in Date.locale) ? lang : 'en';
          return Date.locale[lang].month_names_short[this.getMonth()];
      };
    • Date Locale(Multilingual Support)
      Date.locale = {
          en: {
              month_names: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
              month_names_short: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
          }
      };

      Usage:

      var current_month = new Date().getMonthName(lang);
      var current_short_name = new Date().getMonthNameShort(lang);

      lang parameter is optional

  3. Array

    • Contains (Check if given element exists in Array, similar to jQuery inArray)
      Array.prototype.contains = function(obj) {
          var i = this.length;
          while (i--) {
              if (this[i] === obj) {
                  return true;
              }
          }
          return false;
      }

      Usage:

      ['Red', 'Yellow', 'Green', 'Blue'].contains('Green');
      Output: true
    • Random (Pick a random element from array)
      Array.prototype.random = function () {
          return this[Math.floor((Math.random()*this.length))];
      }

      Usage:

      [1, 2, 3, 4].random();
  4.  Storage

    • Set Object in LocalStorage/SessionStorage
      Storage.prototype.setObject = function(key, value) {
          this.setItem(key, JSON.stringify(value));
      }

      Usage:

      localStorage.setObject('numbers', [1, 2, 3, 4]);
    • Get Object from LocalStorage/Session
      Storage.prototype.getObject = function(key) {
          var value = this.getItem(key);
          return value && JSON.parse(value);
      }

      Usage:

      localStorage.getObject('numbers');