Exploring Unicode in JavaScript to iterate through emojis with different skin tones

Currently, I am facing an issue where Javascript splits emojis with different skin colors into multiple characters instead of treating them as one. Emojis with a yellow skin color work fine and give me the desired results.

For example:

let emojis = [..."πŸ˜‚πŸ˜„πŸ€©πŸ™„πŸ˜πŸ˜£πŸ€©"]

console.log(emojis)
console.log(emojis.length)

However, when dealing with emojis like this, there is a problem as Javascript does not support the use of the [...] operator for these emojis:

let emojis = [..."πŸ§‘πŸΎπŸ‘¨πŸ»πŸ‘§πŸΌπŸ‘¦πŸ½πŸ§’πŸΏ"]

console.log(emojis)
console.log(emojis.length)

I want to find a way to inform Javascript that these are single emojis with a length of one, rather than multiple emojis combined together like in this instance:

let emojis = [..."πŸ‘©β€β€οΈβ€πŸ’‹β€πŸ‘©"]

console.log(emojis)
console.log(emojis.length)

Answer β„–1

When using the spread syntax ... to iterate over strings, the iterator will go through each code point of the string. However, some emojis are made up of multiple code points, causing them to split unintentionally. In newer versions of lodash, you can utilize _.split() to handle emojis and ZWJ characters:

const r1 = _.split("πŸ‘©β€β€οΈβ€πŸ’‹β€πŸ‘©", '');
const r2 = _.split("πŸ§‘πŸΎπŸ‘¨πŸ»πŸ‘§πŸΌπŸ‘¦πŸ½πŸ§’πŸΏ", '');

// Check browser console for results:
console.log(r1, r1.length);
console.log(r2, r2.length);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js" integrity="sha512-WFN04846sdKMIP5LKNphMaWzU7YpMyCU245etK3g/2ARYbPK9Ub18eG+ljU96qKRCWh+quCY7yefSmlkQw1ANQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

It's worth noting that you don't have to import the entire lodash library for this method; you can simply include the method specifically.


Furthermore, there is a stage 4 proposal for Intl.Segmenter, which introduces an API for splitting/separating strings by specifying a granularity level. This involves creating a segmenter that can divide strings based on their graphemes (i.e., visual emoji characters). By using the segmenter on your string, you'll receive an iterator that can be converted into an array of characters with Array.from():

const graphemeSplit = str => {
  const segmenter = new Intl.Segmenter("en", {granularity: 'grapheme'});
  const segitr = segmenter.segment(str);
  return Array.from(segitr, ({segment}) => segment);
}
// Look at browser console for output
console.log(graphemeSplit("πŸ‘©β€β€οΈβ€πŸ’‹β€πŸ‘©")); // ["πŸ‘©β€β€οΈβ€πŸ’‹β€πŸ‘©"]
console.log(graphemeSplit("πŸ§‘πŸΎπŸ‘¨πŸ»πŸ‘§πŸΌπŸ‘¦πŸ½πŸ§’πŸΏ")); // ["πŸ§‘πŸΎ", "πŸ‘¨πŸ»", "πŸ‘§πŸΌ", "πŸ‘¦πŸ½", "πŸ§’πŸΏ"]

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Experiencing issues with implementing shopping cart logic using KnockoutJS. Need help

The Objective Create a dynamic list of products. The Scenario Overview In my online shopping application, I want to showcase the products I add to my shopping list in a sidebar when I click the 'add button' for each product. Brief Problem Sum ...

Can you provide a database of words for different cities, towns, and countries in MongoDB (or in JSON

Currently, I am in the process of developing an application that utilizes MongoDB. One specific feature I am working on implementing is an 'auto-suggest' functionality on the front-end. For example, as a user begins to type the first few letters ...

Encountering a Console warning while working with the Material UI menu. Seeking advice on how to resolve this issue as I am integrating HTML within a text

Caution: PropType validation failed. The prop text provided to LinkMenuItem is invalid as it should be a string, not an object. Please review the render method of Menu. Below is the code snippet: var menuItems = [ // text is not valid text { route: &ap ...

"Struggling with solving an error in METEOR REACT SEARCH and DISPLAY upon user input onChange? Let

Here is the input code snippet: Title: <input type="text" ref="searchTitle" onChange={this.searchTitle}/> This function handles the onChange event: searchTitle(event) { this.setState({ show_article_editable_list: <Article_Editab ...

Unable to locate Node.js /socket.io/socket.io.js on express 4.0

Currently, I am working on implementing a chat feature on my website. During testing on my local server, everything was running smoothly as port 8080 on localhost was readily available. However, after deploying my code to Heroku, I encountered an issue whe ...

Preventing data duplication when refreshing a webpage using Node.js

I am currently utilizing Mustache and Nodejs to populate a dropdown menu with a list of options on my website. However, every time the page is refreshed, I encounter duplicate entries in the dropdown. How can this issue be resolved? I trust that my inquiry ...

Wordpress is experiencing a recurring issue with scripts being loaded multiple times

Currently, I am attempting to load some of my scripts from CDNs such as CDNjs and Google. While the scripts are loading correctly, I have noticed a strange issue where each script seems to generate two or even three HTTP requests (for the same script). You ...

What is the process for turning off deep imports in Tslint or tsconfig?

Is there a way to prevent deep imports in tsconfig? I am looking to limit imports beyond the library path: import { * } from '@geo/map-lib'; Despite my attempts, imports like @geo/map-lib/src/... are still allowed. { "extends": &q ...

Verify if an element with a specific index exists within an array

$.each(constructions, function(i,v) { if ($.inArray(v.name, map[ii].buildings) == -1) {//do something} }; In this scenario, the constructions array consists of unique objects with a name attribute. On the other hand, map[ii].buildings is an array contain ...

Utilizing Javascript to load a vast amount of data onto the browser, followed by initiating an XML

Looking for a solution to send XML requests containing values and content from files obtained by filling out an HTML form. With 5 large files, some exceeding 70 MB, I have implemented JavaScript functions to load file contents and assemble the XML request. ...

Trouble arises when incorporating a new feature onto a map with OpenLayers and Vue.js

I'm currently working on integrating a custom control into my map using OpenLayers with Vue.js. The Explore.vue component is responsible for creating the "map" (olmap) with OL, and I bind it to the child component LeftSideBar2.vue. However, when att ...

The route is displaying the variable as 'undefined' when I attempt to access it

I had set up CRUD for two different models (venues & artists) - venues works fine, but when I try to access 'artists/index', it gives me an error saying 'Artists is not defined'. After examining the code, I believe I need to do two ...

What's causing jQuery to make the entire page malfunction?

I am experiencing an issue where a function is not recognized as being in scope when I have a reference to jQuery defined. Oddly enough, if I comment out that reference, the function call works just fine. I have other pages set up the same way with jQuer ...

Is it true that document.execCommand only works with buttons and not links?

Below is the code snippet I am working with: <div contenteditable="true" style="height:100px;width:100px;border:1px solid; " class="editor"></div> <a class='bold' style="height:10px;width:10px;">B</a> $(function(){ ...

What is the best situation to utilize $(document).ready()?

After observing that using $(document).ready(..) seems to introduce a noticeable delay in applying JavaScript effects, I've been contemplating the best approach. I know that simply placing the effect in a <script> tag may not work if the DOM isn ...

utilizing a pair of API requests within a personalized Alexa skill

I posted a question about integrating Alexa with the Steam custom skill API here, but I realize it might be too detailed for some to read through. In essence, my main question is: Can you make two separate API calls within the same block of JS code while ...

Using JavaScript to assign the title property to an <a> tag

I'm currently working on modifying a code snippet that utilizes jQuery to display the "title" attribute in an HTML element using JavaScript: <a id="photo" href="{%=file.url%}" title="{%=file.name%}" download="{%=file.name%}" data-gallery><i ...

Utilizing util.format to enclose every string within an array with double quotation marks

Currently .. var utility = require("utility"); var carsInput = 'toyota,chevrolet'; var cars = carsInput.split(','); var queryString = utility.format('Cars: [%s]', cars); console.log(queryString); // Cars: [toyota,chevrolet] ...

What are the steps to successfully deploy a static website created with Next.js on Vercel?

Using the Next.js static site generator, I created a simple static site that I now want to deploy on Vercel. However, I keep encountering an error during the build process. While I have successfully deployed this site on other static hosting platforms befo ...

Angular 7+: Trouble with displaying images from assets directory

Details regarding my Angular version: Angular CLI: 7.3.9 Node: 10.15.3 OS: win32 x64 Angular: 7.2.15 ... animations, common, compiler, compiler-cli, core, forms ... language-service, platform-browser, platform-browser-dynamic ... rout ...