首页 > 文章列表 > 如何转换 HTML 标签中的转义字符?

如何转换 HTML 标签中的转义字符?

golang
166 2023-03-08

问题内容

我们如何直接转换"u003chtmlu003e"""? ""to的转换"u003chtmlu003e"很容易使用json.Marshal(),但是json.Unmarshal()相当冗长和麻烦。在 golang 中有没有直接的方法可以做到这一点?

正确答案

您可以使用strconv.Unquote()来进行转换。

您应该注意的一件事是strconv.Unquote()只能取消引用引号中的字符串(例如,以引号字符"或反引号字符开始和结束```),因此我们必须手动附加它。

例子:

// Important to use backtick ` (raw string literal)
// else the compiler will unquote it (interpreted string literal)!

s := `u003chtmlu003e`
fmt.Println(s)
s2, err := strconv.Unquote(`"` + s + `"`)
if err != nil {
    panic(err)
}
fmt.Println(s2)

输出(在Go Playground上试试):

u003chtmlu003e


注意: 要对 HTML 文本进行转义和反转义,可以使用html包。引用其文档:

html 包提供了转义和取消转义 HTML 文本的功能。

但是该html包(特别是html.UnescapeString())不解码形式的 unicode 序列uxxxx,仅&#decimal;&#xHH;.

例子:

fmt.Println(html.UnescapeString(`u003chtmlu003e`)) // wrong
fmt.Println(html.UnescapeString(`<html>`))   // good
fmt.Println(html.UnescapeString(`<html>`)) // good

输出(在Go Playground上试试):

u003chtmlu003e



笔记2:

您还应该注意,如果您编写这样的代码:

s := "u003chtmlu003e"

这个带引号的字符串将不被编译器本身引用,因为它是一个 解释的字符串文字 ,所以你不能真正测试它。要在源代码中指定带引号的字符串,您可以使用反引号来指定 原始字符串文字 ,或者您可以使用 双引号 解释的字符串文字:

s := "u003chtmlu003e" // Interpreted string literal (unquoted by the compiler!)
fmt.Println(s)

s2 := `u003chtmlu003e` // Raw string literal (no unquoting will take place)
fmt.Println(s2)

s3 := "\u003chtml\u003e" // Double quoted interpreted string literal
                           // (unquoted by the compiler to be "single" quoted)
fmt.Println(s3)

输出:


u003chtmlu003e