Advertisement
simeonshopov

String Extention

Jun 20th, 2021
710
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. (function solve() {
  2.   String.prototype.ensureStart = function (str) {
  3.     if (!this.toString().startsWith(str)) { return str + this.toString(); }
  4.     return this.toString();
  5.   };
  6.  
  7.   String.prototype.ensureEnd = function (str) {
  8.     if (!this.toString().endsWith(str)) { return this.toString() + str; }
  9.     return this.toString();
  10.   };
  11.  
  12.   String.prototype.isEmpty = function () { return this.toString().length === 0; };
  13.  
  14.   String.prototype.truncate = function (n) {
  15.     let text = this.toString();
  16.     if (text.length <= n) { return text; }
  17.     else if (n < 4) { return '.'.repeat(n); }
  18.     else {
  19.       text = text.substring(0, n);
  20.       if (text.includes(' ')) {
  21.         let found = true;
  22.         let newtextEnd = undefined;
  23.         while (found) {
  24.           let lastWhiteSpaceIndex = text.lastIndexOf(' ');
  25.           const truncText = `${text.substring(0, lastWhiteSpaceIndex)}...`;
  26.           if (truncText.length <= n) { found = false; newtextEnd = truncText; }
  27.           else { text = text.substring(0, lastWhiteSpaceIndex); }
  28.         }
  29.         return newtextEnd;
  30.       } else { const newtext = text.substring(0, n - 3); return `${newtext}...`; }
  31.     }
  32.   };
  33.  
  34.   String.format = function (string, ...args) {
  35.     for (let i = 0; i < args.length; i++) {
  36.       if (string.includes(`${i}`)) {
  37.         string = string.replace(`{${i}}`, args[i]);
  38.       }
  39.     }
  40.     return string;
  41.   };
  42. })();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement