您可以使用strconv.Unquote()
进行转换。
您应该注意的一件事是,strconv.Unquote()
只能取消引用中的字符串(例如,以引号char "
或反引号char 开头和结尾```),因此我们必须手动附加该字符串。
例:
// Important to use backtick ` (raw string literal)
// else the compiler will unquote it (interpreted string literal)!
s := `\u003chtml\u003e`
fmt.Println(s)
s2, err := strconv.Unquote(`"` + s + `"`)
if err != nil {
panic(err)
}
fmt.Println(s2)
输出(在Go Playground上尝试):
\u003chtml\u003e
<html>
要对HTML文本进行转义和转义,可以使用该html
包。引用其文档:
html包提供用于转义和取消转义HTML文本的功能。
但html
包(具体html.UnescapeString()
)做形式的未解码的unicode序列\uxxxx
,仅&#decimal;
或&#xHH;
。
例:
fmt.Println(html.unescapestring(`\u003chtml\u003e`)) // wrong
fmt.Println(html.unescapestring(`<html>`)) // good
fmt.Println(html.unescapestring(`<html>`)) // good
输出(在Go Playground上尝试):
\u003chtml\u003e
<html>
<html>
您还应该注意,如果您编写如下代码:
s := "\u003chtml\u003e"
该带引号的字符串将由编译器本身取消引用,因为它是一个 解释后的字符串文字 ,因此您无法真正进行测试。要在源代码中指定带引号的字符串,可以使用反引号指定原始字符串文字 ,也可以使用 双引号的 解释字符串文字:
s := "\u003chtml\u003e" // Interpreted string literal (unquoted by the compiler!)
fmt.Println(s)
s2 := `\u003chtml\u003e` // 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)
输出:
<html>
\u003chtml\u003e