Skip to content

Instantly share code, notes, and snippets.

@macedocodigo
Created January 21, 2011 17:18
Show Gist options
  • Save macedocodigo/790019 to your computer and use it in GitHub Desktop.
Save macedocodigo/790019 to your computer and use it in GitHub Desktop.
Reduce a string's length by clipping characters off the end, adding optional characters to the end such as ellipsis
/*
** String prototype for clipping text and optionally adding ellipsis
** Does not modify original variable
** -Example-
** var thisStr = 'Some string of text';
** var newStr = thisStr.clip(10, '...', true); // Some...
** var newStr = thisStr.clip(15, '...', true); // Some string of...
*/
String.prototype.clip = function(len/* Number */, str/* String */, bound/* Boolean */) {
var origLen = len;
if(this.length > len) {
var text = '';
var delimiters = [' ', '-', '_', '.']
if(bound) {
while(text == '' && len > 0) {
var match = false;
var delimit = false;
for(var x=0; x < delimiters.length; x+=1) {
if(this.substr(len,1) == delimiters[x]) {
match = true;
}
if(this.indexOf(delimiters[x]) > -1) {
delimit = true;
}
}
if(delimit == false || match == true) {
text = this.substr(0, len);
} else {
len--;
}
if(len == 0) {
text = this.substr(0, origLen);
}
}
} else {
text = this.substr(0, len);
}
if(str && str != "") {
text = text + str;
}
return text;
}
return this;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment