How to count emoji in a text or string

One option would be to compare the length of the input string against the length of the same string with all Emoji characters removed:

function fancyCount(str){
    return Array.from(str.split(/[\ufe00-\ufe0f]/).join("")).length;
}

var input = "Hello  there";
var output = input.replace(/([\uE000-\uF8FF]|\uD83C[\uDC00-\uDFFF]|\uD83D[\uDC00-\uDFFF]|[\u2694-\u2697]|\uD83E[\uDD10-\uDD5D])/g, "");
console.log("number of Emoji: " + (fancyCount(input) - fancyCount(output)));

I give massive credit to this helpful blog post, which provided the fancyCount() function. This function can detect that certain Emoji characters actually have a width of 2, while other characters have a width of 1. The issue here is one of encoding. Some Emoji characters may take up two bytes, whereas a basic ASCII character (e.g. A-Z) would only take up one byte.

Tags:

Javascript