diff --git a/sanitize.go b/sanitize.go index 2932209..73955bb 100755 --- a/sanitize.go +++ b/sanitize.go @@ -6,6 +6,7 @@ import ( "html" "html/template" "io" + "log" "path" "regexp" "strings" @@ -305,6 +306,19 @@ func Accents(s string) string { return b.String() } +// Get alphanumeric strings only +func Alphanumeric(s string) string { + + // Make a Regex to say we only want + reg, err := regexp.Compile("[^a-zA-Z0-9]+") + if err != nil { + log.Fatal(err) + } + processedString := reg.ReplaceAllString(s, "") + + return processedString +} + var ( // If the attribute contains data: or javascript: anywhere, ignore it // we don't allow this in attributes as it is so frequently used for xss diff --git a/sanitize_test.go b/sanitize_test.go index a2242dc..11e91e9 100644 --- a/sanitize_test.go +++ b/sanitize_test.go @@ -234,3 +234,29 @@ func BenchmarkHTMLAllowed(b *testing.B) { } } } + +var alphanumerics = []Test{ + {"#$ferf*", "ferf"}, + {"aall$%", "aall"}, + {"EFFFG^&", "EFFFG"}, +} + +func TestAlphanumeric(t *testing.T) { + for _, test := range alphanumerics { + output := Alphanumeric(test.input) + if output != test.expected { + t.Fatalf(Format, test.input, test.expected, output) + } + } +} + +func BenchmarkAlphanumeric(b *testing.B) { + for i := 0; i < b.N; i++ { + for _, test := range alphanumerics { + output := Alphanumeric(test.input) + if output != test.expected { + b.Fatalf(Format, test.input, test.expected, output) + } + } + } +}