I have a string in Go as follow:
Hello world ! <a href=\"www.google.com\">Google</a>
the quotes was escaped, and I want to get the string without backward slash.
I tried to use the html.UnescapeString
but not what I want. Is there any solution about my question.
Assuming you are using html/template
, you either want to store the whole thing as a template.HTML
, or store the url as a template.URL
. You can see how to do it here: https://play.golang.org/p/G2supatMfhK
tplVars := map[string]interface{}{
"html": template.HTML(`Hello world ! <a href="www.google.com">Google</a>"`),
"url": template.URL("www.google.com"),
"string": `Hello world ! <a href="www.google.com">Google</a>"`,
}
t, _ := template.New("foo").Parse(`
{{define "T"}}
Html: {{.html}}
Url: <a href="{{.url}}"/>
String: {{.string}}
{{end}}
`)
t.ExecuteTemplate(os.Stdout, "T", tplVars)
//Html: Hello world ! <a href="www.google.com">Google</a>"
//Url: <a href="www.google.com"/>
//String: Hello world ! <a href="www.google.com">Google</a>"
func NewReplacer(oldnew ...string) *Replacer
package main
import (
"bytes"
"fmt"
"log"
"strings"
"golang.org/x/net/html"
)
func main() {
const htm = `
Hello world ! <a href=\"www.google.com\">Google</a>
`
// Code to get the attribute value
var out string
r := bytes.NewReader([]byte(htm))
doc, err := html.Parse(r)
if err != nil {
log.Fatal(err)
}
var f func(*html.Node)
f = func(n *html.Node) {
if n.Type == html.ElementNode && n.Data == "a" {
for _, a := range n.Attr {
out = a.Val
}
}
for c := n.FirstChild; c != nil; c = c.NextSibling {
f(c)
}
}
f(doc)
// Code to format the output string.
rem := `\"`
rep := strings.NewReplacer(rem, " ")
fmt.Println(rep.Replace(out))
}
output :
www.google.com