~netlandish/gobwebs

2e6593919cee2bd315811e4026e6733e95dd6b01 — Peter Sanchez a month ago abe1945
Adding html helper functions
1 files changed, 45 insertions(+), 0 deletions(-)

A core/html.go
A core/html.go => core/html.go +45 -0
@@ 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 `<<br>` not just `<br>`
			if !in {
				start = i

				builder.WriteString(blob[end:start])
			}
			in = true
			continue
		}
		in = false
		end = i + 1
	}
	return builder.String()
}

Do not follow this link