Skip to content

Instantly share code, notes, and snippets.

@sha1sum
Created November 13, 2014 13:08
Show Gist options
  • Save sha1sum/368d6f3b4e2567b89411 to your computer and use it in GitHub Desktop.
Save sha1sum/368d6f3b4e2567b89411 to your computer and use it in GitHub Desktop.
Unicode GroupMe Emoji Replacement
function codePointAt(text, position) {
if (text == null) {
throw TypeError();
}
var string = String(text);
var size = string.length;
// `ToInteger`
var index = position ? Number(position) : 0;
if (index != index) { // better `isNaN`
index = 0;
}
// Account for out-of-bounds indices:
if (index < 0 || index >= size) {
return undefined;
}
// Get the first code unit
var first = string.charCodeAt(index);
var second;
if ( // check if it’s the start of a surrogate pair
first >= 0xD800 && first <= 0xDBFF && // high surrogate
size > index + 1 // there is a next code unit
) {
second = string.charCodeAt(index + 1);
if (second >= 0xDC00 && second <= 0xDFFF) { // low surrogate
// http://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae
return (first - 0xD800) * 0x400 + second - 0xDC00 + 0x10000;
}
}
return first;
};
function replaceEmojiUnicode(text) {
text = text.replace(/([\u2002-\u3299])/g, function(match) {
var code = match.charCodeAt(0);
var codeHex = code.toString(16).toLowerCase();
while (codeHex.length < 4) {
codeHex = "0" + codeHex;
}
return '<img src="https://d2xk3mdboeujlo.cloudfront.net/images/emoji/64/' + codeHex + '.png" class="emoji">';
});
text = text.replace(/([\ud800-\udbff][\udc00-\udfff])/g, function(match) {
var code = codePointAt(match, 0);
var codeHex = code.toString(16).toLowerCase();
while (codeHex.length < 4) {
codeHex = "0" + codeHex;
}
return '<img src="https://d2xk3mdboeujlo.cloudfront.net/images/emoji/64/' + codeHex + '.png" class="emoji">';
});
return text;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment