Skip to content

Instantly share code, notes, and snippets.

@ummjackson
Created January 8, 2023 08:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ummjackson/135d1177d21eb3ff2e70670f928b5108 to your computer and use it in GitHub Desktop.
Save ummjackson/135d1177d21eb3ff2e70670f928b5108 to your computer and use it in GitHub Desktop.
JavaScript function to convert Mastodon custom emoji shortcodes into HTML image tags
/*
This JavaScript function takes "content" value and "emojis" array from a Mastodon API "status" object and converts custom emoji shortcodes into the corresponding HTML image tags.
Example usage, assuming you have just parsed a JSON "status" object from the Mastodon API into a "status" variable:
emojifiedContent = customEmojis(status.content, status.emojis);
You will then want to use CSS to style the ".emoji" class. Example CSS:
.emoji {
width: 16px;
height: 16px;
vertical-align: middle;
object-fit: contain;
margin: -.2ex .15em .2ex;
}
*/
function customEmojis(str, emojis) {
var emojiMap = {};
emojis.forEach(emoji => {
emojiMap[':' + emoji.shortcode + ':'] = '<img src="' + emoji.url + '" draggable="false" class="emoji"/>';
});
emojifiedString = str.replace(/:[\d+_a-z-]+:/g, function (m) {
return emojiMap[m];
});
return emojifiedString;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment