Skip to content

Commit

Permalink
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
extract function
Browse files Browse the repository at this point in the history
mosch committed Jan 8, 2025
1 parent b48a872 commit d4a90d7
Showing 1 changed file with 32 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
export function sanitizeMarkdownForMetatag(
description: string,
maxLength: number = 160,
): string {
if (!description) {
return "";
}

return (
description
// Replace Markdown links [text](url) with just "text"
.replace(/\[([^\]]+)\]\([^)]+\)/g, "$1")
// Remove Markdown image syntax: ![alt](url)
.replace(/!\[.*?\]\(.*?\)/g, "")
// Remove other Markdown syntax (e.g., **bold**, _italic_, `code`)
.replace(/[_*`~]/g, "")
// Remove headings (# Heading), blockquotes (> Quote), and horizontal rules (--- or ***)
.replace(/^(?:>|\s*#+|-{3,}|\*{3,})/gm, "")
// Remove any remaining formatting characters
.replace(/[|>{}[\]]/g, "")
// Collapse multiple spaces and trim the text
.replace(/\s+/g, " ")
.trim()
// Limit to the specified maximum length
.substring(0, maxLength)
.replace(/&/g, "&")
.replace(/</g, "&lt;")
.replace(/>/g, "&gt;")
.replace(/"/g, "&quot;")
.replace(/'/g, "&#039;")
);
}

0 comments on commit d4a90d7

Please sign in to comment.