Skip to content

Instantly share code, notes, and snippets.

@AnatolyUA
Last active December 14, 2015 11:50
Show Gist options
  • Save AnatolyUA/5082344 to your computer and use it in GitHub Desktop.
Save AnatolyUA/5082344 to your computer and use it in GitHub Desktop.
Возвращает строку длиной от min до max $.cutText("some text or <p>Html<p>", min, max); $(".js-story-content-full").cutText(min, max);
(function($){
function cutAt(text, min, max) {
min = min || 0;
if (min == 0) return "";
if(text.length > min){
if (max) {
var BEST = ".!?",
GOOD = ",;",
SPACE = " ",
HELLIP = "&hellip;";
text = text.trim();
var n = max;
for (; BEST.indexOf(text[n]) === -1 && n > min; n--){}
if (n != min || BEST.indexOf(text[n]) !== -1) return text.substr(0, n + 1);
n = max;
for (; GOOD.indexOf(text[n]) === -1 && n > min; n--){}
if (n != min || GOOD.indexOf(text[n]) !== -1) return text.substr(0, n) + HELLIP;
n = max;
for (; SPACE.indexOf(text[n]) === -1 && n > min; n--){}
if (n != min || SPACE.indexOf(text[n]) !== -1) return text.substr(0, n) + HELLIP;
return text.substr(0, max) + HELLIP;
} else {
return text.substr(0, min) + HELLIP;
}
}
return text;
}
$.fn.cutText = function(min, max) {
return cutAt(this.text(), min, max);
};
jQuery.cutText = function(text, min, max){
return cutAt($('<div/>').html(text).text(), min, max);
};
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment