jhlee8804
9/14/2017 - 5:03 AM

String Prototype Extended

'use strict';

(function () {
  if (!String.prototype.format) {
    // like a c# string.format method
    // usage: "{0} of {1}".format('book', 'desk');
    String.prototype.format = function () {
      var args = arguments;
      return this.replace(/{(\d+)}/g, function (match, number) {
        return typeof args[number] != 'undefined' ? args[number] : 'undefined';
      });
    };
  }

  if (!String.prototype.replaceAll) {
    String.prototype.replaceAll = function (target, replacement) {
      return this.split(target).join(replacement);
    };
  }

  if (!String.prototype.isEmpty) {
    String.prototype.isEmpty = function () {
      return (this.length === 0 || !this.trim());
    };
  }

  if (!String.prototype.splice) {
    // |start| 지점에서 |delCount|만큼 삭제한 뒤, |newSubStr| 내용을 삽입.
    // cf. http://stackoverflow.com/questions/4313841/javascript-how-can-i-insert-a-string-at-a-specific-index
    String.prototype.splice = function (start, delCount, newSubStr) {
      return this.slice(0, start) + newSubStr + this.slice(start + Math.abs(delCount));
    };
  }

  if (!String.prototype.removeQueryString) {
    // cf. board?type=list  => 'board'
    String.prototype.removeQueryString = function () {
      return this.split(/[?#]/)[0];
    };
  }

  if (!String.prototype.encodeToHtmlEntity) {
    String.prototype.encodeToHtmlEntity = function () {
      var buf = [];
      for (var i = this.length - 1; i >= 0; i--)
        buf.unshift(['&#', this[i].charCodeAt(), ';'].join(''));

      return buf.join('');
    };
  }

  if (!String.prototype.decodeFromHtmlEntity) {
    String.prototype.decodeFromHtmlEntity = function () {
      return this.replace(/&#(\d+);/g, function (match, dec) {
        return String.fromCharCode(dec);
      });
    };
  }

  if (!String.prototype.btTagToCrlf) {
    // br to CRLF
    String.prototype.btTagToCrlf = function () {
      return this.replace(/<br\s*\/?>/mg, '\n');
    };
  }

  if (!String.prototype.crlfToBrTag) {
    // CRLF to br
    String.prototype.crlfToBrTag = function () {
      return this.replace(/(?:\r\n|\r|\n)/g, '<br />');
    };
  }

  if (!String.prototype.replaceHtmlEntityToTag) {
    // replace html entities to html tag
    String.prototype.replaceHtmlEntityToTag = function () {
      var translate_re = /&(nbsp|amp|quot|lt|gt);/g;
      var translate = {
        'nbsp': ' ',
        'amp': '&',
        'quot': '\"',
        'lt': '<',
        'gt': '>'
      };

      return (this.replace(translate_re, function (match, entity) {
        return translate[entity];
      }));
    };
  }

  if (!String.prototype.removeHtmlEntity) {
    String.prototype.removeHtmlEntity = function () {
      return this.replace(/&(nbsp|amp|quot|lt|gt);/g, '');
    };
  }

  if (!String.prototype.removeHtmlTag) {
    String.prototype.removeHtmlTag = function () {
      return this.replace(/<(?:.|\n)*?>/gm, '');
    };
  }
})();