Replace string with emoji

This is an input field with a code representing emoji. Now I want to replace this code with the appropriate emoji.

The idea was to replace the value with unicode, but that doesn't work for me on inputs. Only when I copy the emoji into the code does the replacement work.

Example:

This code: [e-1f60e]

,
converted: 😎

,
must be: 😎

My question is, how can I convert the given code to 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">
      

Run codeHide result


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

+3


source to share


1 answer


You need...

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]')); // 😎
      

Run codeHide result




For IE compatibility, use String.fromCharCode

either as described here or by directly converting to 16-bit surrogate pairs according to the spec :

// 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]')); // 😎
      

Run codeHide result


+7


source







All Articles