Skip to content

Instantly share code, notes, and snippets.

@vkryukov
Last active August 29, 2015 14:05
Show Gist options
  • Save vkryukov/82c2db13a9293fb4620d to your computer and use it in GitHub Desktop.
Save vkryukov/82c2db13a9293fb4620d to your computer and use it in GitHub Desktop.
Remove HTML attribute from a string.
package main
import (
"bytes"
"fmt"
"strings"
"code.google.com/p/go.net/html"
"code.google.com/p/go.net/html/atom"
)
// RemoveFirstHTMLAttribute removes an attribute from an HTML node and returns the result.
func RemoveFirstHTMLAttribute(node *html.Node, attr string) *html.Node {
var attributes []html.Attribute
for _, a := range node.Attr {
if a.Key != attr {
attributes = append(attributes, a)
}
}
node.Attr = attributes
return node
}
// Render is a helper that renders html.Node as a string.
func Render(h *html.Node) string {
b := new(bytes.Buffer)
html.Render(b, h)
return b.String()
}
// ParseFragment parses a string and returns an html node with no <html><head></head><body>...</body></html> overhead.
func ParseFragment(s string) *html.Node {
n, err := html.ParseFragment(strings.NewReader(s), &html.Node{
Type: html.ElementNode,
Data: "body",
DataAtom: atom.Body,
})
if err != nil {
return nil
}
return n[0]
}
// RemoveAttribute removes an attribute from an HTML string and returns the result.
func RemoveAttribute(s, attr string) string {
n := ParseFragment(s)
if n == nil {
return s
}
return Render(RemoveFirstHTMLAttribute(n, attr))
}
func main() {
const str = "<table style='small' id='this is my id'><tbody><tr><td id='123'>Text</td></tr></tbody></table>"
fmt.Println(RemoveAttribute(str, "id"))
fmt.Println(RemoveAttribute(str, "style"))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment