What is the best way to transform a string into emojis using TypeScript or JavaScript?

Looking to convert emoji from string in typescript to display emoji in html.

Here is a snippet of the Typescript file:

export class Example {
    emoji:any;
    function(){
       this.emoji = ":joy:"
    }
  }

In an HTML file, I would like it to display as: 😂 (this emoji element will be retrieved from the typescript file) Is there a way to achieve this? Any assistance is welcome.

Answer â„–1

To begin, it is essential to establish a mapping system for translating emoticons like :joy: into their respective unicode strings.

For instance, the unicode representation for :joy: would be &#x1f602.

This converted unicode string can then be displayed on the webpage...

Here's a simple example to illustrate this concept.

var emojiMapping = {

":joy:" : "&#x1f602",
  ":shades:": "&#x1f60e",
  ":happy:" : "&#x1f600"

}

var counter = 0;

function displayEmoji(){

  
setInterval(function(){
  if(counter == Object.keys(emojiMapping).length)
counter = 0;
  
  var emojiText = Object.keys(emojiMapping)[counter];
  document.getElementById("displayedEmoji").innerHTML = emojiMapping[emojiText];
counter++;
  }, 500);
}

displayEmoji();
<div id="displayedEmoji">

</div>

Expanding your unicode mapping object with more emojis and implementing a method to replace placeholders (e.g. ":joy:") with corresponding unicode codes for use within sentences will surely enhance the functionality.

Answer â„–2

Here is a method that utilizes an emoji dictionary and a pattern matching algorithm to replace emojis in text:

const emojiDictionary = {
  love: "&#x1f60d",
  laugh: "&#x1f606",
  smile: "&#128512"
}
const regex = /:([^:]*):/g
const inputText = "He was feeling :love: she was laughing :laugh: and we were smiling :smile:"

const replaceEmojis = (pattern, text) => {
  while (result = pattern.exec(text)) {
    text = text.replace(result[0], emojiDictionary[result[1]])
  }
  return text
}

document.getElementById('output').innerHTML = replaceEmojis(regex, inputText)
<div id="output"></div>

By extracting words enclosed within the : symbols using the regEx, we can then use those words (excluding the : as we access them through index [1]) to retrieve the corresponding html code.

Thank you Adriani6 for the user-friendly representation of the emojis!

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

What is the best way to store the result of a mongoose query in a global variable in Node.js?

I retrieved results from the Mongo database and saved them in a variable within a function. However, I am unable to access that variable outside of the function. How can I resolve this issue? Currently, I can see the results inside the function using the ...

Click event not functioning correctly in Internet Explorer

When using jQuery, I have the following code: <script type="text/javascript"> $(document).ready(function(){ $('body').on('click', '.add-photo',function() { $("#images").append($('<input/>').attr(&apo ...

Could someone clarify why EventEmitter leads to issues with global variables?

I recently encountered an error that took me some time to troubleshoot. Initially, I decided to create a subclass of EventEmitter In the file Client.js var bindToProcess = function(func) { if (func && process.domain) { return process.domai ...

What is the best way to perform a single asynchronous or promise-based fetch request and utilize the retrieved data across multiple functions?

Is there a way to optimize fetching data from an API and use the fetched data in multiple methods within the same service without making redundant requests in the Network? export class MediaService { constructor(private mediaAppApiService: MediaAppApiS ...

Rearranging information within a JSON structure

Here is a sample of Javascript object and code to consider: Javascript Object { "thing":{ "data":"some data", "thumb":"some data", "data1":"some data", "data2":"some data", "data3":"some data", }, "extra1":[ ...

Is there a way to utilize jQuery to determine the distance the user has scrolled down?

Looking for some help with changing the style of an element based on scroll position using jQuery. Specifically, I want to add a class name to a div once the user has scrolled beyond 200 pixels and then remove the class name when they scroll back up to l ...

Iterating through a JavaScript object and displaying the outcomes within the identical element

$(document).on('mouseenter', '.grid-img-hover', function() { var container = $(this); var jobId = container.parent().find('.title-wrap-hidden').text(); $.ajax({ url: 'db_client_job_name_lookup.php' ...

Loop through JSON array within an angular controller

I am currently attempting to iterate through a JSON array and display the values on the frontend of my application. I have provided my code, but I'm having trouble retrieving specific values (startDate, endDate) from within the array and displaying th ...

Bootstrap button groups do not support the checking functionality of radio buttons

My bootstrap modal contains a form with two radio style buttons created using the example for normal button styled radio options found here: <form id="changePlanForm" action="/change_plan_submit.php" method="post"> & ...

"Encountered a problem when trying to import stellar-sdk into an Angular

Our team is currently working on developing an app that will interact with the Horizon Stellar Server. As newcomers in this area, we are exploring the use of Angular 8 and Ionic 4 frameworks. However, we have encountered difficulties when trying to import ...

Adjust the dimensions of the canvas without disrupting the existing artwork

I am currently working on a pixel art application where I am facing an issue with saving images from the canvas. The saved image appears small and pixelated when I try to resize it. I would like to resize the image to larger dimensions, but I am unsure of ...

Problem with rendering Ionic v2 HTML in Angular 2

Issue at Hand: Currently, I am developing a hybrid app using Ionic v2 and everything seems to be functioning correctly. When I use ionic serve, the app works as expected in the browser with no issues. However, when I try running the app on an Android devi ...

Unable to adjust the width of a table column within a horizontally scrollable container

I am struggling to resize the columns of a large table with 20 headers. Despite trying to place the table inside a div with overflow:auto, I still cannot achieve horizontal scrolling or make the div expand when resizing the columns. A sample code snippet ...

Nested loops iterating over an array of objects

I am working with a JSON file that contains my data: { "EIC": { "id": "EIC", "text": "Want to do a quick word game?", "replies": ["Sure", "Later"] }, "YMB": { "id": "YMB", "text": "Okay, tomorrow. Cya!", "replies": ["bye Woeb ...

Filtering relations in TypeORM can be achieved by using various query criteria

Hello, I have a couple of questions regarding TypeORM in TypeScript. Using Find() Only: I have two tables in my database - Users and Sessions. I am interested in retrieving a specific User along with all their Sessions where the sessions_deleted_at column ...

Using TypeScript with React: Step-by-step guide to creating a ref prop

I'm currently using Ionic with React (typescript) and working on creating my custom form builder. Within this process, I've created a form that requires a ref property for referencing purposes when in use. My challenge lies in defining a prop tha ...

Tips for setting a uniform width for all bars in apexcharts bar column width

When working with dynamic data, the length of the data should also be variable. For instance, if the data has a length of 24, the column width should be 35px; similarly, even if the data has a length of 2, the column width should still be 35px. Apexchart ...

Issue with the format of incoming data in Ajax post request when working with Django framework

Hello everyone, I am currently working on a script to send a post request to my Django backend. My goal is to have the data in Json format. <input id ="my" type="submit" onclick="me()"/> <script> function me() { var data2 =JSON.stringif ...

Understanding the usage of jQuery transitionend to prevent interruptions in CSS animations

I found a similar thread on StackOverflow but I'm struggling to apply it in my current scenario. The Setup (Welcome Ideas) I've developed a jQuery slider that will have multiple instances on one page, each containing an unknown number of childr ...

I need to compile a comprehensive inventory of all the publicly accessible attributes belonging to a Class/Interface

When working with TypeScript, one of the advantages is defining classes and their public properties. Is there a method to list all the public properties associated with a particular class? class Car { model: string; } let car:Car = new Car(); Object. ...