html - 如何允许在传递给 HTML 值属性的字符串中使用双引号和单引号?

标签 html string vb.net

我有这个 HTML 输入,它应该允许在 value 属性中使用双引号和单引号。

<td><input id="Title" name="Title" class="required" value="$Title$" maxlength="50"/></td> 

它被这个 vb.net 代码取代:

Dim view As New
  StringBuilder(Utils.ReadView("someView.htm"))
        With view
            .Replace("$Title$", EscapeQuote(model.Widget.Title))

我一直在尝试编写 EscapeQuote 来替换双引号的所有实例,用 HTML 等效的 & quot;

    Private Function EscapeDoubleQuotes(ByVal str As String) As String
        str = str.Replace("""", "&quot;")
        'str = str.Replace(Chr(34), "&quot;")
        'str = "'" & str & "'"
        Return str
    End Function

我也尝试过使用 Chr(34) 并将整个字符串括在单引号中。我的工作测试用例是一个像“some string”这样的字符串。 所以在HTML中,value=""some string"",是一个空字符串,输入框留空。

我也试过在 HTML 属性上使用单引号。

value='$Title$'

这允许字符串用双引号括起来,但显然不允许字符串用单引号括起来。

我的头在双引号 hell 中旋转。还有其他我没有尝试过的建议吗?

最佳答案

您可以使用 HttpUtility.HtmlEncode 方法,而不是尝试自己对引号进行编码。它将处理引号和所有其他可能在 HTML 中无效的字符。使用示例:

Imports System
Imports System.Web

Public Module Module1
    Public Sub Main()

        Console.Write(HttpUtility.HtmlEncode("""Hello"""))

    End Sub
End Module

查看实际效果:https://dotnetfiddle.net/7fVVh0

关于html - 如何允许在传递给 HTML 值属性的字符串中使用双引号和单引号?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42864502/

相关文章:

javascript - 从服务器上的 html 发送数据 (node.js)

html - 减少 "subscribe"按钮的宽度

javascript - 如果 "webpage not found"则重定向到不同页面?

MySQL:将字符串转换为德语的 float /小数

c# - 多个启动项目之间的 Visual Studio 延迟?

javascript - 如何向跨度添加鼠标悬停效果?

python - 确保字符串中没有整数?

c++ - 定义复合静态字符串

c# - 在 .NET 中的 CLR 上下文中,堆栈空间是如何分配的

vb.net - IISExpress乱码HTTP 500错误信息