Skip to content

Instantly share code, notes, and snippets.

@serweb-labs
Created May 22, 2020 00:06
Show Gist options
  • Save serweb-labs/775c18de414feae3e84b429cb3640be8 to your computer and use it in GitHub Desktop.
Save serweb-labs/775c18de414feae3e84b429cb3640be8 to your computer and use it in GitHub Desktop.
two functions tocheck if a text is emoji regular expression based and canvas based
// regular expression based
function isEmoji(text) {
return (new RegExp(/[\uD800-\uDBFF]/g).test(text) && new RegExp(/[\uDC00-\uDFFF]/g).test(text));
}
// canvas bases, slow and depend if the system can draw the emoji
function isEmojiCanvas(text) {
const ArrayLikeToString = arg => Array.prototype.toString.call(arg);
const getTextFeature = (text, color) => {
try {
const canvas = document.createElement('canvas')
canvas.width = 1;
canvas.height = 1;
const ctx = canvas.getContext('2d');
ctx.textBaseline = 'top';
ctx.font = '100px "Segoe UI Emoji", "Segoe UI Symbol", "Segoe UI", "Apple Color Emoji", "Twemoji Mozilla", "Noto Color Emoji", "EmojiOne Color", "Android Emoji"';
ctx.fillStyle = color;
ctx.scale(0.01, 0.01);
ctx.fillText(text, 0, 0);
return ctx.getImageData(0, 0, 1, 1).data
} catch (e) {
return false
}
}
const feature1 = getTextFeature(text, '#000');
const feature2 = getTextFeature(text, '#fff');
if (feature1 && feature2) {
const feature1Str = ArrayLikeToString(feature1)
const feature2Str = ArrayLikeToString(feature2)
return feature1Str === feature2Str && feature1Str !== '0,0,0,0';
}
return false;
}
const text = "😚 hello 🤭, how are you? 👌"
console.log("regular expression based:")
// don't use foreach
// or the emoji is splitted
for (const ch of text) {
if (isEmoji(ch)) {
console.log("is emoji", ch)
}
else {
console.log("no is emoji", ch)
}
}
console.log("canvas based based:")
// don't use foreach
// or the emoji is splitted
for (const ch of text) {
if (isEmojiCanvas(ch)) {
console.log("is emoji", ch)
}
else {
console.log("no is emoji", ch)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment