GoMoji

repository·main·Indexed 42 days ago

https://github.com/forpelevin/gomoji

A high-performance Go library for detecting, removing, replacing, and looking up emoji metadata in strings. It handles Unicode grapheme clusters and provides functions such as ContainsEmoji, RemoveEmojis, and GetInfo to retrieve detailed Emoji struct metadata including slugs, Unicode names, and groups.

Tokens
2.5K
Snippets
12
Records
14
Agent score
4%

What's inside GoMoji

  1. Security considerations for GoMoji

    main

    When using GoMoji, keep the following security and technical constraints in mind:

    • Not a Sanitizer: GoMoji is a string-processing library, not a security sanitizer. Do not use it to prevent XSS or injection attacks; use a dedicated HTML/markup sanitizer for that.
    • Grapheme Clusters: Detection and replacement operate on Unicode grapheme clusters. Do not assume that one code point equals one visible symbol.
    • Variation Selectors: Variation selectors are stripped during processing to normalize output. If your application requires preserving exact variation selectors, avoid using RemoveEmojis or Replace* methods.
    • Untrusted Output: When using ReplaceEmojisWithSlug, treat the resulting string as untrusted user-controlled input and escape/encode it appropriately for your output context.
  2. Quick Start with GoMoji

    main

    GoMoji allows you to detect and remove emojis from strings. Here is a minimal example of how to check for emoji presence and remove them:

    package main
    
    import (
        "fmt"
        "github.com/forPelevin/gomoji"
    )
    
    func main() {
        s := "Hello 👋 world 🦋"
        fmt.Println(gomoji.ContainsEmoji(s)) // true
        fmt.Println(gomoji.RemoveEmojis(s))  // "Hello  world "
    }
  3. Check for, find, and remove emojis

    main

    Use these core functions to manipulate emoji content in strings:

    • ContainsEmoji(s string) bool: Returns true if the string contains any emoji.
    • FindAll(s string) []Emoji: Returns a slice of Emoji structs containing all unique emojis found in the string.
    • CollectAll(s string) []Emoji: Returns a slice of Emoji structs for all emojis found, including repeats, preserving their order.
    • RemoveEmojis(s string) string: Returns the string with all emojis removed.
    // Check for emojis
    hasEmoji := gomoji.ContainsEmoji("hello world 🤗")
    
    // Find all unique emojis
    emojis := gomoji.FindAll("🧖 hello 🦋 world")
    
    // Remove emojis
    cleaned := gomoji.RemoveEmojis("🧖 hello 🦋 world")
  4. Get detailed emoji information

    main

    You can look up metadata for a specific emoji character using GetInfo. This returns an Emoji struct containing details like the slug, Unicode name, and group. If the input is not a valid emoji, it returns ErrStrNotEmoji.

    info, err := gomoji.GetInfo("🦋")
    if err == nil {
        fmt.Println(info.Slug)        // "butterfly"
        fmt.Println(info.UnicodeName) // "E3.0 butterfly"
        fmt.Println(info.Group)       // "Animals & Nature"
    }
  5. Replace emojis in strings

    main

    GoMoji provides several ways to replace emojis with different types of content:

    • ReplaceEmojisWith(s string, c rune) string: Replaces every emoji with a single specified character (rune).
    • ReplaceEmojisWithSlug(s string) string: Replaces every emoji with its unique text slug (e.g., 🦋 becomes butterfly).
    • ReplaceEmojisWithFunc(s string, replacer func(Emoji) string) string: Replaces every emoji using a custom callback function that receives the Emoji struct.
    // Replace with a specific character
    replaced := gomoji.ReplaceEmojisWith("🧖 hello 🦋 world", '_')
    
    // Replace with slugs
    slugs := gomoji.ReplaceEmojisWithSlug("🧖 hello 🦋 world")
    
    // Replace with custom function
    custom := gomoji.ReplaceEmojisWithFunc("🧖 hello 🦋 world", func(em gomoji.Emoji) string {
        return em.Slug
    })
  6. Reference the Emoji struct

    main

    The Emoji struct represents the metadata associated with an emoji character:

    FieldTypeDescription
    SlugstringUnique identifier (e.g., "butterfly")
    CharacterstringThe actual emoji character
    UnicodeNamestringOfficial Unicode name
    CodePointstringUnicode code point
    GroupstringEmoji group category
    SubGroupstringEmoji subgroup category
    type Emoji struct {
        Slug        string `json:"slug"`        // Unique identifier
        Character   string `json:"character"`   // The emoji character
        UnicodeName string `json:"unicode_name"` // Official Unicode name
        CodePoint   string `json:"code_point"`  // Unicode code point
        Group       string `json:"group"`       // Emoji group category
        SubGroup    string `json:"sub_group"`    // Emoji subgroup category
    }
  7. Get detailed information about an emoji with GetInfo

    main

    Use GetInfo(emoji string) (Emoji, error) to retrieve the metadata for a specific emoji character or cluster. If the provided string is not a recognized emoji, it returns ErrStrNotEmoji.

    info, err := gomoji.GetInfo("🚀")
    if err != nil {
        if errors.Is(err, gomoji.ErrStrNotEmoji) {
            fmt.Println("Not an emoji")
        }
    }
    fmt.Printf("Name: %s, CodePoint: %s\n", info.UnicodeName, info.CodePoint)
  8. Extract all emojis from a string with CollectAll and FindAll

    main

    The library provides two ways to extract emojis from a string:

    1. CollectAll(s string) []Emoji: Returns all occurrences of emojis found in the string. If an emoji appears multiple times, it will appear multiple times in the resulting slice.
    2. FindAll(s string) []Emoji: Returns a unique set of emojis found in the string. It uses a map internally to ensure no duplicate emoji entities are returned.
    // Returns every instance found
    instances := gomoji.CollectAll("😀😀 test 😀") 
    
    // Returns only unique emojis found
    unique := gomoji.FindAll("😀😀 test 😀") 
  9. Remove or replace emojis in a string

    main

    You can modify strings containing emojis using several methods:

    • RemoveEmojis(s string) string: Returns a new string with all emojis removed.
    • ReplaceEmojisWith(s string, c rune) string: Replaces every emoji with a specific rune.
    • ReplaceEmojisWithSlug(s string) string: Replaces every emoji with its text slug (e.g., :rocket:).
    • ReplaceEmojisWithFunc(s string, replacer func(Emoji) string) string: The most flexible method; allows you to provide a custom function that takes an Emoji object and returns a replacement string.
    // Remove
    clean := gomoji.RemoveEmojis("Hi 🚀!") // "Hi !"
    
    // Replace with rune
    withX := gomoji.ReplaceEmojisWith("Hi 🚀!", '?') // "Hi ?!"
    
    // Replace with slug
    withSlug := gomoji.ReplaceEmojisWithSlug("Hi 🚀!") // "Hi rocket!"
    
    // Custom replacement
    custom := gomoji.ReplaceEmojisWithFunc("Hi 🚀!", func(e gomoji.Emoji) string {
        return "[" + e.Slug + "]"
    }) // "Hi [rocket]!"
  10. Retrieve all available emojis with AllEmojis

    main

    Call AllEmojis() []Emoji to get a sorted slice of all emoji entities supported by the library's internal provider.

    all := gomoji.AllEmojis()
    for _, em := range all {
        fmt.Printf("%s: %s\n", em.Character, em.Slug)
    }
  11. Check if a string contains emojis with ContainsEmoji

    main

    Use ContainsEmoji(s string) bool to determine if a given string contains any emoji characters. It efficiently skips ASCII-only strings and uses grapheme segmentation to identify complex emoji clusters.

    if gomoji.ContainsEmoji("Hello 🚀") {
        fmt.Println("String contains emojis!")
    }