Last active
December 23, 2019 00:28
-
-
Save diamondburned/74c7a229be6e43cd8bd0b05ddb7d529b to your computer and use it in GitHub Desktop.
Escaping @everyone in Go
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// EscapeEveryone escapes @everyone and @here mentions. | |
func EscapeEveryone(s string) string { | |
var mentionBuf string | |
var mentionInd int | |
for i, r := range s { | |
if r == '@' && i != len(s)-1 { | |
mentionBuf += string(r) | |
mentionInd = i | |
continue | |
} | |
if unicode.IsSpace(r) { | |
mentionBuf = "" | |
continue | |
} | |
if mentionBuf != "" && unicode.IsLetter(r) { | |
mentionBuf += string(r) | |
} | |
if stringsCmp(mentionBuf, "@everyone", "@here") { | |
s = s[:mentionInd+1] + "\u200b" + s[mentionInd+1:] | |
// Reset buffer | |
mentionBuf = "" | |
mentionInd = 0 | |
} | |
} | |
return s | |
} | |
func stringsCmp(str string, cmp ...string) bool { | |
for _, c := range cmp { | |
if c == str { | |
return true | |
} | |
} | |
return false | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func TestEscapeEveryone(t *testing.T) { | |
var samples = [...]string{ | |
"@everyone", | |
"@\u202eeveryone", | |
} | |
for _, sample := range samples { | |
esc := EscapeEveryone(sample) | |
if !strings.HasPrefix(esc, "@\u200b") { | |
t.Fatal("Escape failed:", fmt.Sprintf("%#v", esc)) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment