您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

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

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

您可以使用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(`&#60;html&#62;`))   // good
fmt.Println(html.unescapestring(`&#x3c;html&#x3e;`)) // 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
其他 2022/1/1 18:15:30 有453人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶