Escape Strings Before They Reach HTML
Neutralize user-controlled text before it reaches HTML: EscapeString turns angle brackets and quotes into entities, and UnescapeString restores them.
Code
package main
import (
"fmt"
"html"
)
func main() {
// User-controlled text concatenated straight into an HTML page is executed as markup
comment := `<script>alert("xss")</script> & "quotes" 'apostrophes'`
// EscapeString turns < > & ' " into entities: the browser renders them as plain text
fmt.Println(html.EscapeString(comment))
// UnescapeString reverses entities back into characters
escaped := "Tom & Jerry <3"
fmt.Println(html.UnescapeString(escaped))
// Escaping grows the string: lengths of the original, once-escaped, and double-escaped forms
single := html.EscapeString(comment)
double := html.EscapeString(single)
fmt.Println("orig:", len(comment), "escaped:", len(single), "double:", len(double))
}The flow inside the file
Escape Strings Before They Reach HTML comes down to the function main.
What to watch for
- No external packages — everything relies on the language’s built-in APIs.
Using it
Signature: func main()
Running the file prints labeled results such as orig: — each operation’s effect is visible in the output.
Key statements
single := html.EscapeString(comment)
Interactive Tools for This Topic
HTML Entity Encoder / DecoderEncode the five HTML-significant characters and decode named or numeric entities, with optional numeric encoding for non-ASCII text.Regex Escape GeneratorEscape plain text so it can be embedded safely in a JavaScript RegExp, covering all metacharacters like dots, brackets, braces, and backslashes.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.Argon2id Hash InfoEstimate Argon2id password-hash latency and memory usage, and check your parameters against OWASP 2024 minimum and recommended settings.
FAQ
- What does Escape Strings Before They Reach HTML print when run?
- Run it as a complete program — the output lines carry labels such as `orig:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.