Advertisement
Guest User

Untitled

a guest
Apr 28th, 2017
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. String.prototype.limit = function( limit, userParams) {
  2.     var text = this
  3.       , options = {
  4.             ending: '...'  // что дописать после обрыва
  5.           , trim: true     // обрезать пробелы в начале/конце?
  6.           , words: true    // уважать ли целостность слов?
  7.         }
  8.       , prop
  9.       , lastSpace
  10.       , processed = false
  11.     ;
  12.  
  13.     //  проверить limit, без него целого положительного никак
  14.     if( limit !== parseInt(limit)  ||  limit <= 0) return this;
  15.  
  16.     // применить userParams
  17.     if( typeof userParams == 'object') {
  18.         for (prop in userParams) {
  19.             if (userParams.hasOwnProperty.call(userParams, prop)) {
  20.                 options[prop] = userParams[prop];
  21.             }
  22.         }
  23.     }
  24.  
  25.     // убрать пробелы в начале /конце
  26.     if( options.trim) text = text.trim();
  27.  
  28.     if( text.length <= limit) return text;    // по длине вписываемся и так
  29.  
  30.     text = text.slice( 0, limit); // тупо отрезать по лимиту
  31.     lastSpace = text.lastIndexOf(" ");
  32.     if( options.words  &&  lastSpace > 0) {  // урезать ещё до границы целого слова
  33.         text = text.substr(0, lastSpace);
  34.     }
  35.     return text + options.ending;
  36. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement