What is the process for transforming Unicode symbols into their corresponding emojis?

I have been working on a project similar to the one showcased on this website. I've managed to successfully convert UTF16 into UTF string using the code snippet below:

function decodeFBEmoji (fbString) {
  // Convert String to Array of hex codes
  const codeArray = (
    fbString  
    .split('')
    .map(char => (
      char.charCodeAt(0)  
    )
  );  

  // Convert plain JavaScript array to Uint8Array
  const byteArray = Uint8Array.from(codeArray);

  // Decode byte array as a UTF-8 string
  return new TextDecoder('utf-8').decode(byteArray); 

Now, my next challenge is to extract the Unicode from a text string and replace it with its decoded counterpart to display as an emoji without altering the rest of the text. However, when attempting to use regex for extracting the Unicode string, I encounter issues.

function replaceEmoji(text){
      let str = "lorem ipsum lorem ipsum \u00e2\u009d\u00a4\u00ef\u00b8\u008f lorem ipsum"; 
      let res = str.match(/[\\]\w+/g); 
      console.log(str);
      console.log(res); 
}

Check out the console output of the above code here

Edit: Here's the regex pattern that I tested

Answer №1

Trying to decipher UTF8 may become challenging when mixing JS string escapes with bytes.

For instance, using \uXXXX represents an escape for a Unicode codepoint (similar to how \n works for a newline). So, it's accurate to say that

"\u0041" == "A"

The reason your regex fails to match is due to the absence of a backslash \ in the string. The form in which your UTF8 data arrives may vary, but if it's in byte format, decoding can be done like this:

const utf8 = new Uint8Array(
    Array.prototype.map.call(
        "lorem ipsum lorem ipsum \u00e2\u009d\u00a4\u00ef\u00b8\u008f lorem ipsum", 
        c => c.charCodeAt(0)
    )
);
console.log(new TextDecoder('utf8').decode(utf8));

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

Displaying real-time server responses using jQuery, PHP, and AJAX

Is there a way to display server response in real-time as it is being sent during a long and time-consuming request? Scenario: 1) A JQuery function sends an AJAX request to the server and opens a Dialog widget to wait for the response to update the conte ...

The installation of package.json is unsuccessful, as it will only proceed with an empty name and version

Having trouble installing the package.json file after updating to the latest version of Node on my Windows PC. When trying to run npm, an error was thrown. Any help would be greatly appreciated. Command Prompt C:\Users\Felix\Desktop\ ...

The onchange event is failing to trigger any JavaScript function

I am facing an issue where the onchange event of a dropdown menu is not triggering at all. I even tried redirecting it to a simple JavaScript function for testing purposes, but that didn't work either. I'm struggling to find a solution. Below is ...

Issue occurs when using Angular Firebase $createUser method

I'm stuck on this issue. I'm attempting to set up a user with AngularFire using $firebaseAuth instead of the deprecated FirebaseSimpleLogin, as advised in the documentation. I am confident that the form is submitting a valid email and password, b ...

The jQuery prop("disabled") function is not operating as expected

Although I've seen this question answered multiple times, none of the suggested solutions seem to be working for my specific example. Hopefully, a fresh set of eyes can help me figure out what's going wrong. Even after adding alerts to confirm t ...

Removing a dynamic TypeScript object key was successful

In TypeScript, there is a straightforward method to clone an object: const duplicate = {...original} You can also clone and update properties like this: const updatedDuplicate = {...original, property: 'value'} For instance, consider the foll ...

I'm currently attempting to determine the total cost of a series of operations, however, I am not receiving any results

Here is the code snippet from my HTML file: <tr> <td><input id="z1" type="number" oninput="calculateSubTotal()"> </td> <td>Shirts - WASH - Qty 1 to 4</td> <td>2.50 ea</td> ...

Initiating a file download using HTML

When I try to initiate a download by specifying the filename, instead of downloading, it opens in a new tab. The code snippet below shows what I am currently using. Additionally, I am working on Chrome Browser. <!DOCTYPE html> <html> < ...

The command "bin" is not identified as an internal or external command in this npm script

I'm new to using node/npm and encountering an issue when attempting to start an npm script. Every time I try to execute a simple script like the one below, I get the error message "bin is not recognized as an internal or external command." I have suc ...

Adjusting the Scaling Value to Match the Browser's Scaling Value

I'm struggling with a problem in HTML where the initial-scale function is not working as expected. When I zoom in on certain pages, it saves the zoom level. However, when I navigate to another page and then return to the original one, the zoom level r ...

Implement a jQuery loading animation triggered by scrolling down the page

Can anyone offer guidance on how to trigger an animation as you scroll down a webpage? I've come across this feature while browsing through this website: I would love to include code examples, but I'm unsure of where to start with implementing t ...

When it comes to TypeScript, one can always rely on either event.target or event

I'm a beginner with TypeScript and currently in the process of refactoring an arrow function within React.js. Here is the current implementation: handleChange = (event): void => { const target = event.target || event.srcElement; this.s ...

The scroll event is triggered only when scrolling upwards

I am encountering an issue with my scroll function. Currently, it only alerts when scrolling to the top instead of the bottom. How can I correct this so that it triggers the alert when reaching the bottom of the page? $(window).scroll(function() { if ...

The necessity of utilizing a dummy object for storing events in JavaScript is evident in certain situations

I am confused as to why in some instances a dummy object is needed in JavaScript to store events, like in the following code: Metal.Gold = function() { var temp = $("<div>"); //dummy object this.Submit = function(url1, method, data){ ...

What is the best way to extract specific information from an API using AJAX and Axios?

I can't figure out what I'm doing wrong when trying to access a URL from an API using Axios. For instance, I'm attempting to select the following URL: "https://media4.giphy.com/media/yy6hXyy2DsM5W/giphy-downsized.gif?cid=482277c2s3j1s8uell6v ...

Using jQuery to update elements with the same class in HTML

This morning, I stumbled upon a rather perplexing issue. Despite my attempts to find a solution on SO, all I came across were methods involving data loading into HTML or a complete page refresh. My aim is to utilize jQuery's $.ajax function to update ...

Utilizing jQuery to extract information from a JSON string

Currently, I have a set of records stored in an Oracle table and I am retrieving them using the following PHP code: $json_OutputArray = array(); while ($result = oci_fetch_assoc($parse_submitted_list)) { $json_OutputArray[] = $result; } $jsonstring ...

Error in finding the element with Selenium webdriver 2.0 was encountered

I can't seem to find the element with the specified class name. Here's a snippet of the HTML code: <a class="j-js-stream-options j-homenav-options jive-icon-med jive-icon-gear" title="Stream options" href="#"></a> I attempted to gen ...

Using JSON to dynamically add data points to all series in Highcharts

I am looking to dynamically generate a chart that displays network usage over time. The number of series in the chart can vary depending on the number of network adapters present in the system at any given moment. I have developed a script that retrieves ...

Transforming a collection of Javascript objects into a pure Javascript array

After JSON.stringify-ing my JavaScript object, the output looks like this: [ { "item_id": null, "parent_id": "none", "depth": 0, "left": "1", "right": 4 }, { "item_id": "1", "parent_id": ...