1

Let's say I have a string as such:

var text = "Hi ";

I want to store this text in a database and wish to convert the emoji's to unicode.

My current solution is to convert the string to an array. Then convert each character to unicode.

 function toUnicode(text){
    var arr = Array.from(text);
    var unicodeArr = [];
    for (let i = 0; i < arr.length; i++) {
        var unicode = arr[i].codePointAt(0).toString(16);
        unicodeArr.push(unicode);
    }
    return JSON.stringify(unicodeArr);
}

Here are the output when I run the code:

var text = "Hi ";

var unicodeArr = toUnicode(text);
console.log(unicodeArr); //["48","69","20","1f602","1f602"]

The only issue is that I'm not sure how to convert this back to a whole string.

Is there a much more easy solution to store this var text = "Hi "; in a Database?

SunAwtCanvas
  • 1,261
  • 1
  • 13
  • 38

2 Answers2

0

I modified your "toUnicode" function to return an array of numbers and not a jsonified array of number.toString, so I didn't have to parse it all again to unpack it. Give this a try:

function toUnicode(text){
  return Array.from(text).map(char => char.codePointAt(0));  
}

function fromUnicode(unicode) {
  return unicode.map(num => String.fromCodePoint(num)).join("");
}

var text = "Hi ";
var unicodeArr = toUnicode(text);
var backToString = fromUnicode(unicodeArr);
console.log(text, unicodeArr, backToString);
James
  • 20,957
  • 5
  • 26
  • 41
0

You can convert to base64 which is platform agnostic:

var text = "Hi ";

const b64 = btoa(unescape(encodeURIComponent(text)));
const txt = decodeURIComponent(escape(atob(b64)));

console.log(b64);
console.log(txt);
n--
  • 3,563
  • 4
  • 9