Fichtelgard

Text kürzen

export function shortenString(string: string, length: number): string {
if (string.length <= length) return string;
return string.substring(0, length) + " ...";
}
export function truncateString(string: string, length: number): string {
if (string.length <= length) return string;
let processedString: string = string;
processedString = bbCodeApply(processedString);
processedString = stripTags(processedString);
return truncateStringKeepWords(processedString, length);
}

export function truncateStringKeepWords(
string: string,
desiredLength: number,
processedString?: string,
wordsArray?: string[],
currentIndex?: number
): string {
if (currentIndex && currentIndex > 50) return string;
if (string.length <= desiredLength) return string;
if (processedString && wordsArray && currentIndex) {
if (wordsArray.length === currentIndex) {
return processedString;
}
const newIndex = currentIndex + 1;
let newString = processedString + " " + wordsArray[newIndex];
if (newString.length > desiredLength) return processedString + " ...";
return truncateStringKeepWords(
string,
desiredLength,
newString,
wordsArray,
newIndex
);
}
const stringParts: string[] = string.split(" ");
if (stringParts.length === 0) return string;
if (stringParts.length === 1) {
if (stringParts[0].length > desiredLength) {
return shortenString(stringParts[0], desiredLength);
} else {
return string;
}
}
let newString = stringParts[0];
return truncateStringKeepWords(
string,
desiredLength,
newString,
stringParts,
1
);
}