All files / src/lib/seo title.ts

100% Statements 9/9
100% Branches 6/6
100% Functions 1/1
100% Lines 7/7

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27                    1x               7x 5x 3x 3x 3x   7x    
/**
 * SEO title helpers.
 *
 * Search engines (incl. Bing Site Scan) flag `<title>` text longer than ~60
 * characters as "Title too long". Editorial titles can run much longer, so the
 * primary fix is an editor-set `metaTitle`; this helper is the backstop that
 * keeps the rendered `<title>` within budget when no `metaTitle` is provided.
 */
 
/** Max length of the full rendered `<title>` (including brand suffix). */
export const TITLE_MAX_LEN = 60;
 
/**
 * Clamp a title's text to `maxLen` at a word boundary. Returns the input
 * unchanged when it already fits. No ellipsis (cleaner in SERPs); trailing
 * separators/punctuation left by the cut are stripped.
 */
export function clampTitleText(text: string, maxLen: number): string {
	if (maxLen <= 0) return "";
	if (text.length <= maxLen) return text;
	const slice = text.slice(0, maxLen);
	const lastSpace = slice.lastIndexOf(" ");
	const cut = lastSpace > 0 ? slice.slice(0, lastSpace) : slice;
	// Drop a trailing separator/punctuation/space left dangling by the cut.
	return cut.replace(/[\s–—:;,.-]+$/u, "");
}