guumaster
6/14/2013 - 5:11 PM

string methods slugify and dasherize

string methods slugify and dasherize

!(function() {
  "use strict";

  var VERSION = '1.4.0';

  var ENTITIES = {};
  function S(s) {
    if (s !== null && s !== undefined) {
      if (typeof s === 'string')
        this.s = s;
      else
        this.s = s.toString();
    } else {
      this.s = s; //null or undefined
    }

    this.orig = s; //original object, currently only used by toCSV() and toBoolean()

    if (s !== null && s !== undefined) {
      if (this.__defineGetter__) {
        this.__defineGetter__('length', function() {
          return this.s.length;
        })
      } else {
        this.length = s.length;
      }
    } else {
      this.length = -1;
    }
  }

  var __nsp = String.prototype;
  var __sp = S.prototype = {
    //#modified from https://github.com/epeli/underscore.string
    dasherize: function() {
      var s = this.trim().s.replace(/[_\s]+/g, '-').replace(/([A-Z])/g, '-$1').replace(/-+/g, '-').toLowerCase();
      return new S(s);
    },
      slugify: function() {
      var sl = (new S(this.s.replace(/[^\w\s-]/g, '').toLowerCase())).dasherize().s;
      if (sl.charAt(0) === '-')
        sl = sl.substr(1);
      return new S(sl);
    },
    trim: function() {
      var s;
      if (typeof __nsp.trim === 'undefined') 
        s = this.s.replace(/(^\s*|\s*$)/g, '')
      else 
        s = this.s.trim()
      return new S(s);
    }    
    
  };

function Export(str) {
    return new S(str);
  }

  //attach exports to StringJSWrapper
  Export.VERSION = VERSION;
  Export.TMPL_OPEN = '{{';
  Export.TMPL_CLOSE = '}}';
  Export.ENTITIES = ENTITIES;
  
   window.S = Export;

}).call(this);