3 回答

TA貢獻1876條經驗 獲得超6個贊
使用 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

TA貢獻1848條經驗 獲得超2個贊
假設您正在使用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 ! <a href="www.google.com">Google</a>"

TA貢獻1874條經驗 獲得超12個贊
我想得到沒有反斜杠的字符串。
這是一個簡單的問題,但是對于這樣一個簡單的問題,現有的兩個答案都太復雜了。
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))
}
在https://play.golang.org/p/7XX7jJ3FVFt試試
- 3 回答
- 0 關注
- 240 瀏覽
添加回答
舉報