-1

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.

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
kenticny
  • 507
  • 2
  • 8
  • 20

3 Answers3

2

Use strings.NewReplacer()

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

ASHWIN RAJEEV
  • 2,525
  • 1
  • 18
  • 24
0

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 ! &lt;a href=&#34;www.google.com&#34;&gt;Google&lt;/a&gt;&#34;
dave
  • 62,300
  • 5
  • 72
  • 93
  • 1
    It's possible OP is referring to using templates but the question gives no indication that's the case, making this a pretty big assumption. – Adrian Dec 07 '18 at 14:39
0

I want to get the string without backward slash.

It's a simple ask but both existing answers are way too complicated for such simple ask.

package main

import (
    "fmt"
    "strings"
)

func main() {
    s := `Hello world ! <a href=\"www.google.com\">Google</a>`
    fmt.Println(s)
    fmt.Println(strings.Replace(s, `\"`, `"`, -1))
}

Try it at https://play.golang.org/p/7XX7jJ3FVFt

HTH

xpt
  • 20,363
  • 37
  • 127
  • 216