Clms
Clms

Reputation: 733

Replace string with emoji

Given is an input field with an code representing an emoji. I now want to replace this code with the corresponding emoji.

The idea was to substitute the value with the unicode but that does not work for me in inputs. Only when I copy the emoji itself into the code, the replacement works.

Example:

Given code: [e-1f60e],
converted: 😎,
should be: 😎

My question: how can I convert the given code to the emoji inside JavaScript?

$("#tauschen").click(function() {
  $('#blub').val(function(index, value) {
    return value.replace('[e-1f60e]', '😎'); // Doesn't work
  });
});

$("#tauschen2").click(function() {
  $('#blub2').val(function(index, value) {
    return value.replace('[e-1f60e]', '😎'); // Works - but how to convert the given string to an emoji?!
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>
  Given are strings in an imout field like these, representing an emoji: <strong>[e-1f60e]</strong> </p>

<p>
 Now I want to display them "live" as emojis, instead of only the code: &#x1f60e;
</p>

<input id="blub" type="text" name="test" value="[e-1f60e]">
<input type="submit" value="Test 1" id="tauschen">
<br>

<input id="blub2" type="text" name="test" value="[e-1f60e]">
<input type="submit" value="Test 2" id="tauschen2">

JSFiddle: https://jsfiddle.net/r07qnuoz/1/

Upvotes: 3

Views: 3086

Answers (1)

le_m
le_m

Reputation: 20248

You need to...

  1. ...find or extract the hexadecimal code point within the string
  2. ...convert that hexadecimal string to a number
  3. ...convert that code point number to a string via String.fromCodePoint

function convertEmoji(str) {
  return str.replace(/\[e-([0-9a-fA-F]+)\]/g, (match, hex) =>
    String.fromCodePoint(Number.parseInt(hex, 16))
  );
}

console.log(convertEmoji('[e-1f60e]')); // 😎

For compatibility with IE, use String.fromCharCode either as detailed here or by direct conversion to 16-bit surrogate pairs according to the specification:

// Convert supplementary plane code point to two surrogate 16-bit code units:
function surrogate(cp) {
  return [
    ((cp - 0x010000 & 0xffc00) >> 10) + 0xd800,
    (cp - 0x010000 & 0x3ff) + 0xdc00
  ];
}

function convertEmoji(str) {
  return str.replace(/\[e-([0-9a-fA-F]+)\]/g, function(match, hex) {
    return String.fromCharCode.apply(null, surrogate(Number.parseInt(hex, 16)))
  });
}

console.log(convertEmoji('[e-1f60e]')); // 😎

Upvotes: 9

Related Questions