Skip to content

Commit

Permalink
feat: sanitize and prepare HTML content for Medium
Browse files Browse the repository at this point in the history
  • Loading branch information
rnag committed Feb 12, 2024
1 parent eecf523 commit 4a3d6a0
Showing 1 changed file with 41 additions and 1 deletion.
42 changes: 41 additions & 1 deletion src/converter.js
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,47 @@ function converter(content, allowUnsafe = false) {
content = content.replace(/^\{[ \t]*%.+%[ \t]*}$/gm, '');
}

return marked(content);
return cleanedContentForMedium(marked(content));
}

function cleanedContentForMedium(htmlContent) {
return (
htmlContent
// This is mainly to address code blocks that
// have two consecutive blank lines.
//
// Otherwise, Medium seems to split code blocks
// at this terminator.
.replace(/(\r\n|\r|\n){2}/g, '\n \n')
// This is to address bulleted list items in
// markdown that have a blank line between them.
//
// Medium seems to render them with a blank bulleted
// list item in between, otherwise.
.replace(
/<li>[\r\n]*<p>(.*)<\/p>[\r\n]*<\/li>/g,
'<li>$1</li>'
)
// This will replace embed links to other sites (I think
// Medium calls them mixtape embeds) so that they will be
// properly formatted in the post preview.
//
// The only thing needed is a manual `return` key press when
// cursor is at the end of the text.
.replace(
/<blockquote>[\r\n]*<p><a href="(.*)"><strong>.*<\/strong><\/a><\/p>[\r\n]*<\/blockquote>/g,
'<p><a href="$1">$1</a></p>'
)
// This will get rid of extraneous blank lines at the start and end
// of blockquotes that show up in the Medium editor otherwise.
.replace(
/<blockquote>[\r\n]*<p>(.*)<\/p>[\r\n]*<\/blockquote>/g,
'<blockquote><em>$1</em></blockquote>'
)
// This will replace markdown-flavor text inside underscore
// like `_{ anything }_` with `<em>{ anything }</em>`
.replace(/_([^\n]+)_/g, '<em>$1</em>')
);
}

export default converter;

0 comments on commit 4a3d6a0

Please sign in to comment.