Skip to content

Instantly share code, notes, and snippets.

@mwunsch
Created December 16, 2012 01:24
Show Gist options
  • Save mwunsch/4301954 to your computer and use it in GitHub Desktop.
Save mwunsch/4301954 to your computer and use it in GitHub Desktop.
Replace emoji characters in a string with an image of said emoji.
// (c) 2012 Mark Wunsch http://markwunsch.com
// MIT license.
if (!String.fromCodePoint) {
/*!
* ES6 Unicode Shims 0.1
* (c) 2012 Steven Levithan <http://slevithan.com/>
* MIT License
*/
String.fromCodePoint = function fromCodePoint () {
var chars = [], point, offset, units, i;
for (i = 0; i < arguments.length; ++i) {
point = arguments[i];
offset = point - 0x10000;
units = point > 0xFFFF ? [0xD800 + (offset >> 10), 0xDC00 + (offset & 0x3FF)] : [point];
chars.push(String.fromCharCode.apply(null, units));
}
return chars.join("");
}
}
(function (root, factory) {
if (typeof define === 'function' && define.amd) {
define([], factory);
} else {
root.emoji = factory();
}
}(this, function () {
var emoji = {},
EMOJI_HEX_TO_TUPLE;
var EMOJI_HEX_TO_TUPLE = {
"1f604" : ["http://www.emoji-cheat-sheet.com/graphics/emojis/smile.png", "smiling face with open mouth and smiling eyes"]
}
var hexToEmoji = emoji.hexToEmoji = function (hex) {
var codepoint = parseInt(hex, 16);
return String.fromCodePoint(codepoint);
}
function emojiPatterns (hex) {
return new RegExp(hexToEmoji(hex), "g");
}
function imageTagFromTuple (tuple) {
return '<img src="'+tuple[0]+'" alt="'+tuple[1]+'" style="width: 1em;" />';
}
emoji.imageReplace = function replaceEmojiWithImage (input) {
var buffer = input,
tuple;
for (var hex in EMOJI_HEX_TO_TUPLE) {
if (EMOJI_HEX_TO_TUPLE.hasOwnProperty(hex)) {
tuple = EMOJI_HEX_TO_TUPLE[hex];
buffer = buffer.replace(emojiPatterns(hex), imageTagFromTuple(tuple));
}
}
return buffer;
}
return emoji;
}));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment