4

I have added an emoji into html code having written its dec representation inside a div - " &#128512 "; How do I get the numeral presentation of πŸ˜€? I need to process a string containing both - text and emojis and the emoji should be represented in numeral view. So , if I have a string containing - "hello world πŸ˜€" , it should be replaced to "hello world &#128512 ;"

document.onreadystatechange = function(){
if(document.readyState == "complete"){
       document.getElementById("area").addEventListener("keypress" ,      public_mode);
   }
}

function public_mode(event){
 var key = event.key;
  if(key === "Enter") {
     event.preventDefault();
     sendMessage(this);
   }
}

function sendMessage(area){
 console.log(area.innerHTML);
 area.innerHTML = "";
}
#area {
    padding: 5px;
 width: 170px;
 border:1px solid black;
    }
<div id = "area" contenteditable="true">How to get it in dec - &#128512;</div>
skoriy
  • 186
  • 10

2 Answers2

2

You can get the number of a character by .codePointAt():

console.log(`&#${ ("".codePointAt(0)) };`)

This (combined with a loop) can solve your problem:

function encodeEmoji(str){
    let output = ""
    for(let i = 0; i < str.length; i++){
        const codePoint = str.codePointAt(i)
        //don't encode common characters
        if(codePoint > 9727)
            output += `&#${ codePoint };`
        else
            output += str[i]
    }
    return output
}

 console.log(encodeEmoji("hello world "))
FZs
  • 16,581
  • 13
  • 41
  • 50
  • This does not fit on account of a string can content russian chars and ukrainian. So , the chars will be represented in numeral view. – skoriy May 09 '19 at 20:41
  • @Sckoriy Ok, then you can modify the 'accepted' charcode range in the if condition. Additionally, characters encoded with this will show as normal if displayed as HTML – FZs May 09 '19 at 20:48
  • @Sckoriy I've edited my answer accordingly. Now it only converts emojies... Take a look at it! – FZs May 09 '19 at 21:02
  • 1
    as an idea , I can not check if the value is an emoji.I've decided I will get whole string and process it by encode.It doesn't really matter how the content will be saved in a database. – skoriy May 09 '19 at 21:02
  • @Sckoriy I've done a little research, and found the emoji range: chars>9727 are emojies... – FZs May 09 '19 at 21:05
  • @FZs: i have to convert \uD83D\uDE0A to 128512 this format.can you help me please? – Kapil Soni Jun 26 '20 at 13:15
0

You can use codePointAt (returns a non-negative integer that is the Unicode code point value).

let emoji = area.innerHTML.split('- ')[1];
console.log(emoji.codePointAt(0));
ludovico
  • 2,103
  • 1
  • 13
  • 32