owncast/utils/strings.go
John Regan 3f65099910
Name change: better unicode handling (#3164)
* Name change: better unicode handling

Client-side:

* Changes the NameChangeModal to show text "Over limit" when a proposed display
name is too long.

* Allows names to go over limit to prevent splitting graphemes on input.

Server-side:

* Changes the MakeSafeStringOfLength to count number of unicode code points
instead of string bytes.

* name modal: check that newName is defined before iterating
2023-07-11 10:44:09 -07:00

33 lines
735 B
Go

package utils
import (
"strings"
"github.com/microcosm-cc/bluemonday"
)
// StripHTML will strip HTML tags from a string.
func StripHTML(s string) string {
p := bluemonday.NewPolicy()
return p.Sanitize(s)
}
// MakeSafeStringOfLength will take a string and strip HTML tags,
// trim whitespace, and limit the length.
func MakeSafeStringOfLength(s string, length int) string {
newString := s
newString = StripHTML(newString)
// Convert utf-8 string into Unicode code points.
codePoints := []rune(newString)
if len(codePoints) > length {
codePoints = codePoints[:length]
}
newString = string(codePoints)
newString = strings.ReplaceAll(newString, "\r", "")
newString = strings.TrimSpace(newString)
return newString
}