Created
May 22, 2020 00:06
Revisions
-
serweb-labs created this gist
May 22, 2020 .There are no files selected for viewing
This file contains hidden or 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 charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,61 @@ // 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) } }