Как убрать кавычки в HTML-строке - PullRequest
0 голосов
/ 07 декабря 2018

У меня в Go строка:* но не то, что я хочу.Есть ли решение по моему вопросу.

Ответы [ 2 ]

0 голосов
/ 07 декабря 2018

Использовать строки. NewReplacer ()

func NewReplacer (oldnew ... строка) * 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))
    }

вывод:

www.google.com

0 голосов
/ 07 декабря 2018

Предполагая, что вы используете html/template, вы либо хотите сохранить все это как template.HTML, либо сохранить URL-адрес как template.URL.Вы можете посмотреть, как это сделать здесь: 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 ! &lt;a href=&#34;www.google.com&#34;&gt;Google&lt;/a&gt;&#34;
...