javascriptregex

How to remove all characters from string apart from emoji


This function currently removes all emoji characters from a string using regex. How can I reverse this so it removes all characters apart from the emoji characters?

var ranges = [
  '\ud83c[\udf00-\udfff]', // U+1F300 to U+1F3FF
  '\ud83d[\udc00-\ude4f]', // U+1F400 to U+1F64F
  '\ud83d[\ude80-\udeff]'  // U+1F680 to U+1F6FF
];

function removeEmoji() {
  var str = $('#emoji').html();
 
  str = str.replace(new RegExp(ranges.join('|'), 'g'), '');
  $("#emoji").html(str);
}

$('button').on('click', function() {
  removeEmoji();
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="emoji">
  <li>πŸ˜ŽπŸ˜ŽπŸ˜ŽπŸŽπŸ˜ŽπŸ’¨</li>
  <li>or Smiling Face</li>
  <li>or 😎 SπŸ’¨miling 😎😎😎Face</li>
  <li>or Smiling Face</li>
  <li>πŸ˜ŽπŸ˜ŽπŸŽπŸ™‰πŸ˜Ž</li>
  <li>or SmilπŸ’¨ing Face</li>
  <li>or 😎 Smiling πŸ˜ŽπŸ™‰πŸ˜ŽFace</li>
  <li>or πŸ’¨πŸŽSmiling Face</li>
</ul>

<button>Push Me</button>


Solution

  • Just replace str.replace() with str.match()!

    Note that I have copied this snippet from your answer, and it is getting and replacing the entire html of the <ul>. This includes the <li> elements.

    var ranges = [
      '\ud83c[\udf00-\udfff]', // U+1F300 to U+1F3FF
      '\ud83d[\udc00-\ude4f]', // U+1F400 to U+1F64F
      '\ud83d[\ude80-\udeff]'  // U+1F680 to U+1F6FF
    ];
    
    function removeNonEmoji() {
      var str = $('#emoji').html();
     
      str = str.match(new RegExp(ranges.join('|'), 'g'), '');
      $("#emoji").html(str);
    }
    
    $('button').on('click', function() {
      removeNonEmoji();
    })
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <ul id="emoji">
      <li>πŸ˜ŽπŸ˜ŽπŸ˜ŽπŸŽπŸ˜ŽπŸ’¨</li>
      <li>or Smiling Face</li>
      <li>or 😎 SπŸ’¨miling 😎😎😎Face</li>
      <li>or Smiling Face</li>
      <li>πŸ˜ŽπŸ˜ŽπŸŽπŸ™‰πŸ˜Ž</li>
      <li>or SmilπŸ’¨ing Face</li>
      <li>or 😎 Smiling πŸ˜ŽπŸ™‰πŸ˜ŽFace</li>
      <li>or πŸ’¨πŸŽSmiling Face</li>
    </ul>
    
    <button>Push Me</button>