iterate through all text on a page and remove any emojis in javascript

One way to remove emojis from a string in JavaScript is to use Regular Expressions to match and remove any characters that are classified as emojis. Here's an example function that iterates through all text on a page and removes any emojis:

index.tsx
function removeEmojisFromPage() {
  // Select all elements that contain text on the page
  const elementsWithText = document.querySelectorAll('body *');

  // Iterate through each element and remove any emojis
  elementsWithText.forEach(function(element) {
    // Get the text content of the element
    const text = element.textContent;
    
    // Replace any emojis with an empty string
    const regex = /[\u{1F600}-\u{1F64F}]|[\u{1F300}-\u{1F5FF}]|[\u{1F680}-\u{1F6FF}]|[\u{2600}-\u{26FF}]/gu;
    const textWithoutEmojis = text.replace(regex, '');
    
    // Set the new text content of the element
    element.textContent = textWithoutEmojis;
  });
}
659 chars
18 lines

This code selects all elements on the page that contain text, iterates through each element, and uses a Regular Expression to replace any emojis with an empty string. The Regular Expression used in this example matches all emojis in the Unicode ranges \u{1F600}-\u{1F64F}, \u{1F300}-\u{1F5FF}, \u{1F680}-\u{1F6FF}, and \u{2600}-\u{26FF}. The u and g flags are used to ensure that all emojis in the text are replaced. Finally, the new text content of the element is set without any emojis.

gistlibby LogSnag