Advertisement
Liliana797979

string extension - js advanced

Oct 13th, 2021
146
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. (function() {
  2.     String.prototype.ensureStart = function(str) {
  3.         let toStr = this.toString();
  4.         if (toStr.startsWith(str)) {
  5.             return toStr;
  6.         } else {
  7.             return str+toStr;
  8.         }
  9.     }
  10.     String.prototype.ensureEnd = function (str) {
  11.         let toStr = this.toString();
  12.         if (toStr.endsWith(str)) {
  13.             return toStr;
  14.         } else {
  15.             return toStr+str;
  16.         }
  17.     }
  18.  
  19.     String.prototype.isEmpty = function () {
  20.         return this.length == 0;
  21.     }
  22.  
  23.     String.prototype.truncate = function (n) {
  24.         const toStr = this.toString();
  25.         if (this.length <= n) {
  26.             return this.toString();
  27.         }
  28.         if (this.length < 4) {
  29.             let str = toStr.substr(0,this.length-n);
  30.             str = str + ".".repeat(n);
  31.             return str;
  32.         } else {
  33.             const splitted = toStr.split(" ");
  34.             if (splitted.length == 1) {
  35.                 return toStr.substr(0, n-3) + "...";
  36.             } else {
  37.                 let result = "";
  38.                 for (let i = 0; i < splitted.length; i++) {
  39.                     if (result.length + splitted[i].length <= n-3) {
  40.                         result += " " + splitted[i];
  41.                     } else {
  42.                         return result.trim() + "...";
  43.                     }
  44.                 }
  45.                 return result + "...";
  46.             }
  47.         }
  48.     }
  49.  
  50.     String.format = function(str,...params) { //params = [5,7,12];
  51.         // let result = str.substring(0, str.indexOf(`{${0}}`));
  52.         let result = str;
  53.         //"Ivan{1} Ivanov"
  54.  
  55.         for (let i = 0; i < params.length; i++) {
  56.             result = result.replace(`{${i}}`, params[i]);
  57.         }
  58.         return result;
  59.     }
  60. })()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement