Um aus einem langen Text einen Teasertext zu extrahieren, hilft diese Funktion. Optional kann die Länge (default 120), das Trennzeichen und die Zeichenfolge angegeben werden, welche hinter dem Teasertext erscheinen soll.
/**
* @param {string} text
* Necessary
* @param {int} length
* Optional. If not specified, 120 is used
* @param {string} seperator
* Optional. If not specified, the next character after the separator that is in the array seperators is used
* @param {string} dotDotDot
* Optional. If nothing is used, three dots are attached to the teaser text
* @returns the Teasertext
*/
const getTeaser = function(text, length, seperator, dotDotDot) {
let newText = [];
let slicerCounts = [];
let seperators = ['. ', ', ', ': ', '; ', '- '];
let slicerCount = 0;
seperator = (typeof seperator !== 'undefined') ? seperator : seperators;
dotDotDot = (typeof dotDotDot !== 'undefined') ? dotDotDot : '...';
length = (typeof length !== 'undefined') ? length : 120;
newText[0] = text.substr(0, length);
newText[1] = text.substr(length);
if (Array.isArray(seperator)) {
for (let index in seperator) {
if (newText[1].indexOf(seperator[index])!==-1) {
slicerCounts[index] = newText[1].indexOf(seperator[index]);
}
}
if(slicerCounts.length!==0){
slicerCount = Math.min.apply(Math, slicerCounts);
}
} else {
slicerCount = newText[1].indexOf(seperator);
}
if(slicerCount===0){
return newText[0] + dotDotDot;
}
return newText[0] + newText[1].substr(0, slicerCount) + dotDotDot;
}