Special Double Line Ellipsis Handling v2
by mmansion
HTML
<h1>Ellipsis Formating Test</h1>
<hr>
<h1>Movie Titles</h1>
<p>BridesMaids:MKG HD</p>
<p>La Otra Familia HD</p>
<p>127 hours</p>
<p>Dolphin Tales</p>
<p>bridesmaids: Mkg HD</p>
<p>Bridesmaides: Now in HD</p>
<p>Final Destination 5 HD</p>
<hr>
<h1>Output</h1>
<div id="title_0" class="title"></div>
<div id="title_1" class="title"></div>
<div id="title_2" class="title"></div>
<div id="title_3" class="title"></div>
<div id="title_4" class="title"></div>
<div id="title_5" class="title"></div>
<div id="title_6" class="title"></div>
CSS
.title {
width: 170px;
height: 50px;
background: lightblue;
border: thin solid black;
font-weight: bold;
font-size: 20px;
text-align: center;
}
h1 {
font-weight: bold;
}
JavaScript
function format(str, maxLength, keepOneLine) {
var ellip = "\u2026"
var line1, line2; //two lines allocated for titles
//HANDLE ELLIPSIS CASES
if (keepOneLine) {
if (str.length <= maxLength) {
line1 = str;
} else {
line1 = str.substr(0, (maxLength - 1)) + ellip;
};
return line1;
} else if (str.length > maxLength) { //if last char on line1 char
var tmpStr = str.substr(0, maxLength);
var breakIx;
if (tmpStr.match(/\:/)) {
//create two lines - break at color
breakIx = str.indexOf(":");
line1 = str.substr(0, breakIx + 1);
line2 = str.substr(breakIx + 1, str.length - 1);
} else if (tmpStr.charAt(tmpStr.length - 1).match(/[a-z]/i)) {
var lastChar = tmpStr.charAt(tmpStr.length - 1);
var charIx = maxLength;
var isSpace = false;
while (!isSpace && charIx > 0) { //backstep on first line; look for place to break
--charIx;
if (tmpStr.charAt(charIx) === " ") {
isSpace = true; //found place to break first line
breakIx = charIx;
}
}
if (isSpace) {
//WITH ellipsis on 1st line
line1 = str.substr(0, breakIx);
line2 = str.substr(charIx, str.length - 1);
} else {
//WITH ellipsis on 1st AND 2nd lines
line1 = str.substr(0, maxLength - 1) + ellip;
line2 = str.substr(str.indexOf(' '), str.length - 1);
}
} else {
line1 = tmpStr;
line2 = str.substr(maxLength, str.length - 1);
}
if (line2.length > maxLength) {
line2 = line2.substr(0, maxLength - 1) + ellip;
}
return line1 + "<br>" + line2;
} else {
//NO ellipsis necessary
return str;
}
}
var titles =...