Created
January 8, 2023 08:16
-
-
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 file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
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