How to find emoji from strings by golang?

Issue

I want to find if emoji is exists and replace to string(HTML unicode). (rune to string)

for example, this is the sentence

"i like you hahahah 😀 hello."

to this is result.

"i like you hahahah &#128512 hello."

the emoji and the emoji position are randomly.


I will use upper code in below code.

    import "golang.org/x/text/encoding/korean"

    strings_with_emoji = "i like you hahahah 😀 hello."
    var euckrEnc = korean.EUCKR.NewEncoder()
    euckrSubject, err := euckrEnc.String(strings_with_emoji)

there are no value of emoji.
https://uic.io/ko/charset/show/euc-kr/

so I got the error is ERRO[0002] encoding: rune not supported by encoding.

Solution

We can convert string to []rune and every rune convert to ASCII or HTML entity

package main

import (
    "log"
    "strconv"
)

func main() {
    inp := "i like you hahahah 😀 hello."

    res := ""
    runes := []rune(inp)
    
    for i := 0; i < len(runes); i++ {
        r := runes[i]
        if r < 128 {
            res += string(r)
        } else {
            res += "&#" + strconv.FormatInt(int64(r), 10) + ";"
        }
    }

    log.Printf("result html string: %v", res)
}

Answered By – Maksim Fedorov

Answer Checked By – Jay B. (GoLangFix Admin)

Leave a Reply

Your email address will not be published.