-
HUX布斯
使用 strings.NewReplacer()func NewReplacer(oldnew ...string) *替换器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)) }输出 :www.google.com
-
慕尼黑5688855
假设您正在使用html/template,您要么希望将整个内容存储为template.HTML,要么将 url 存储为template.URL。您可以在此处查看操作方法:https ://play.golang.org/p/G2supatMfhKtplVars := 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>"
-
HUWWW
我想得到没有反斜杠的字符串。这是一个简单的问题,但是对于这样一个简单的问题,现有的两个答案都太复杂了。package mainimport ( "fmt" "strings")func main() { s := `Hello world ! <a href=\"www.google.com\">Google</a>` fmt.Println(s) fmt.Println(strings.Replace(s, `\"`, `"`, -1))}在https://play.golang.org/p/7XX7jJ3FVFt试试