HttpUtility.HtmlDecode() exept some specific strings in vb.net

Actually, I wanted to HTMLDecode a text using HttpUtility.HtmlDecode() function and it works properly with whole text, but I want to decode the text except some specific string. How can I do that?

Specifically, I don't want to decode < and >

Let's say my string is - &lt; &amp; &gt;

HttpUtility.HtmlDecode(text) returns - < & >

Wanted Output - &lt; & &gt;

Upvotes: 0

Views: 631

Answers (1)

the_lotus
the_lotus

Reputation: 12748

You could replace the strings you don't want to change to something the decoder will not recognize then bring them back to the original value. You need to make sure that the string you replace to is not something that can be found in the string normally.

Public Function Convert1(ByVal str As String) As String

    str = str.Replace("&lt;", "{lt}")
    str = str.Replace("&gt;", "{gt}")

    str = HttpUtility.HtmlDecode(str)

    str = str.Replace("{lt}", "&lt;")
    str = str.Replace("{gt}", "&gt;")

    Return str
End Function

An other option would be to split of your string and Decode only the part you want.

Public Function Convert2(ByVal str As String) As String

    Dim parts() As String = Regex.Split(str, "(&lt;|&gt;)")

    For i As Integer = 0 To parts.Length - 1
        Console.WriteLine(parts(i))
        If parts(i) <> "&lt;" And parts(i) <> "&gt;" Then
            parts(i) = HttpUtility.HtmlDecode(parts(i))
        End If
    Next

    Return String.Join("", parts)
End Function

This is just a sample, some check and refactoring would need to be done.

Upvotes: 0

Related Questions