Advertisement
kstoyanov

05. String Extension

Oct 13th, 2020
166
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. (function () {
  2.   String.prototype.isEmpty = function () {
  3.     return this == '';
  4.   };
  5.   String.prototype.ensureStart = function (str) {
  6.     if (this.startsWith(str)) return this.toString();
  7.     return str + this.toString();
  8.   };
  9.   String.prototype.ensureEnd = function (str) {
  10.     if (this.endsWith(str)) return this.toString();
  11.     return this.toString() + str;
  12.   };
  13.   String.prototype.truncate = function (n) {
  14.     if (this.length < 4) return '.'.repeat(n);
  15.     if (this.length <= n) return this.toString();
  16.     if (this.indexOf(' ') == -1) {
  17.       return `${this.slice(0, n - 3)}...`;
  18.     }
  19.     const tokens = this.split(' ');
  20.     let result = tokens[0];
  21.     for (let i = 1; i < tokens.length; i++) {
  22.       if (result.length + tokens[i].length + 4 > n) // space + '...'
  23.       { return `${result}...`; }
  24.       result += ` ${tokens[i]}`;
  25.     }
  26.   };
  27.   String.format = function (str) {
  28.     for (let i = 1; i < arguments.length; i++) str = str.replace(`{${i - 1}}`, arguments[i]);
  29.     return str;
  30.   };
  31. }());
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement