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

Enhance your Vue app with filtered categories using Vue-google-chart

What is the process for creating a filter category in a bar chart using the vue-google-charts wrapper in Vue.js? I have successfully created a stacked bar chart and now I am looking to add a filter by label inside the legend. Here is my vue application: ...

Issue with JavaScript HTML Section Changer not functioning properly

I need to implement a button that switches between two pages when pressed. Although the code seems simple, I am struggling to make it work. HTML <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"& ...

Activate the search function once the user has finished entering text

Currently facing the following issue: Within my JavaScript file, I have the below code snippet, termChange(evt) { this.rows = []; this.searchTerm = evt.target.value; this.getCases(); } This section of code clears out the ...

What is the process of creating a new array by grouping data from an existing array based on their respective IDs?

Here is the initial array object that I have: const data = [ { "order_id":"ORDCUTHIUJ", "branch_code":"MVPA", "total_amt":199500, "product_details":[ { ...

A pop-up window displaying an electron error message appears, but no errors are logged in the console

In a Nutshell: While developing a single-page website with Electron, I encountered the common issue of jQuery not being globally accessible. To tackle this problem, I decided to simplify it by using a quick start example, but unfortunately, I'm strugg ...

Is it possible to utilize a computed property for dynamically styling a table row based on certain conditions?

I have a table of users that I am currently rendering, and my goal is to highlight the entire row only for the current user. My initial thought was to use a computed property to achieve this, but I seem to be facing some difficulties in making it work. I ...

Guide to creating a Map with typescript

I've noticed that many people are converting data to arrays using methods that don't seem possible for me. I'm working with React and TypeScript and I have a simple map that I want to render as a list of buttons. Here is my current progres ...

Using JavaScript to dynamically invoke a function and pass parameters dynamically

Exploring a dynamic method call with parameters in JavaScript. let obj = { method: 'foo1', params: ['one', 'two'] } foo1(p1, p2) { // do something } To execute it => [obj.method](obj.params) Is there a way to dyn ...

Bringing Together AngularJS and JQuery: Using $(document).ready(function()) in Harmony with Angular Controller

Can you lend me a hand in understanding this? I have an angular controller that is structured like so: angular.module('myApp', []) .controller('ListCtrl', function($scope, $timeout, $http){ // Making API calls for Health List ...

Effective Angular - ensuring all API calls are completed in a forEach loop before returning the final array

Struggling with the asynchronous nature of Angular, I'm faced with a challenge. My task involves looping through various cards where certain types require API calls while others do not. However, upon completion of the loop, only the cards that do not ...

Dynamic image updates in real-time

Beginning a new project and already facing a roadblock, I could really use some assistance. I have 16 (4x4) images that I am displaying on a page. $max_images = $_GET['images']; $num_images = $max_images; while (($num_images > 0) && ...

Issue with Web Worker functionality in SvelteKit on Firefox version 106.0.5

I've set up a function in my main file like this: const loadWorker = async () => { const SyncWorker = await import("$lib/canvas.worker?worker"); syncWorker = new SyncWorker.default(); syncWorker?.postMessage({}); ...

Determine the time left and check the speed of file uploads using ajax with jquery or javascript

Here is a snippet of code using jQuery.ajax to handle file uploads with progress tracking functionality. The function updates the DOM elements with information about bytes uploaded, total bytes, and percentage completed. However, I am looking for addition ...

Inquiry about how TypeScript handles object property references when passed into functions

As a newcomer to TypeScript, I am exploring the creation of a range slider with dual handles using D3.js. I have developed a simple class for managing the slider objects: export class VerticalRangeSlider{ private sliderContainer: d3.Selection<SVGG ...

What You See Is What You Get - A versatile tool for editing both text and

As a developer, I have encountered a common need that StackOverflow addresses. Situation I am in the process of creating a website where users can post code examples and articles using an admin system. These posts may be created by me or registered fron ...

The Ion slider's onFinish event is triggered when the page loads, independent of any user interaction with the slider

I am facing an issue with ionslider. I have observed that the plugin triggers the onFinish action without any user interaction when the page is loaded. However, on the demo site ionden.com/a/plugins/ion.rangeSlider/demo_interactions.html, the plugin only r ...

Is there a method to incorporate a scroll event into the ng-multi-selectdropdown, a npm package?

Query: I need to incorporate a scroll event in the given html code that triggers when the div is scrolled. However, I am facing issues with implementing a scroll event that works when the elements are being scrolled. <ng-mult ...

"Enhance Your Website with Bootstrap Modal and Jazz up Your

I am encountering an issue with modal-bootatrap and bootstrap-datepicker. Within the datatable, there is a button provided for editing. Upon clicking the edit button, a modal-bootstrap will be displayed. The modal-bootstrap contains a form for editing d ...

What is the most effective way to send URL strings to the server-side click handler in a jQuery loop using $.each method?

As I work with URL values in my client-side script, I aim to generate links that can transmit these URL values back to my server-side click handler upon clicking. The server-side code /logclick logs the timestamp and destination of the click for auditing p ...

The functionality of a generated button has been compromised

My goal is to create a webshop that doesn't rely on MySQL or any database, but instead reads items from JSON and stores them in LocalStorage. However, I've encountered an issue where the functionality of buttons gets lost after using AJAX to gene ...