From 2e6593919cee2bd315811e4026e6733e95dd6b01 Mon Sep 17 00:00:00 2001 From: Peter Sanchez Date: Mon, 10 Feb 2025 07:19:12 -0600 Subject: [PATCH] Adding html helper functions --- core/html.go | 45 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 core/html.go diff --git a/core/html.go b/core/html.go new file mode 100644 index 0000000..43d3b5c --- /dev/null +++ b/core/html.go @@ -0,0 +1,45 @@ +package core + +import ( + "strings" + "unicode/utf8" +) + +// StripHtmlTags helper function strip all <> tags from a string. For more +// features/control use something like the bluemonday module. +// Adapted from the following SO answer: https://stackoverflow.com/a/64701836 +func StripHtmlTags(blob string) string { + var ( + builder strings.Builder + htmlTagStart rune = 60 // Unicode `<` + htmlTagEnd rune = 62 // Unicode `>` + start, end int = 0, 0 + in bool + ) + builder.Grow(len(blob) + utf8.UTFMax) + + for i, c := range blob { + if (i+1) == len(blob) && end >= start { + builder.WriteString(blob[end:]) + } + + if c != htmlTagStart && c != htmlTagEnd { + continue + } + + if c == htmlTagStart { + // Only update the start if we are not in a tag. + // This make sure we strip out `<
` not just `
` + if !in { + start = i + + builder.WriteString(blob[end:start]) + } + in = true + continue + } + in = false + end = i + 1 + } + return builder.String() +} -- 2.45.3