Jonathan Wood
Jonathan Wood

Reputation: 67295

Correct Way to Encode HTML Page Title

I have an ASP.NET WebForms application. I'm setting the page's title based on content from my database.

Because this content is entered by the user, it can contain any characters, including ones that could be interpreted as HTML markup. Therefore, I am HTML-encoding this content before setting the title.

But I see this is causing problems by producing overly encoded results:

<title>Hoigaard&amp;#39;s Nordic Walking Tuesdays</title>

What is the correct way to safely encode text used to set the title tag?

Upvotes: 4

Views: 1940

Answers (2)

mellamokb
mellamokb

Reputation: 56779

I tested this, and it appears setting Page.Title already performs the encoding. So your additional encoding is resulting in double-encoded results. Just set the Page.Title directly:

Page.Title = "Test & Testing";

result:

<title>Test &amp; Testing</title>

Upvotes: 3

feeela
feeela

Reputation: 29932

Use some function similar to the PHP function htmlspecialchars():

<%
' Copyright (c) 2009, reusablecode.blogspot.com; some rights reserved.
' This work is licensed under the Creative Commons Attribution License.

' Convert special characters to HTML entities.
function htmlspecialchars(someString)
    ' Critical that ampersand is converted first, since all entities contain them.
    htmlspecialchars = replace(replace(replace(replace(someString, "&", "&amp;"), ">", "&gt;"), "<", "&lt;"), """", "&quot;")
end function
%>

source: http://snipplr.com/view/12207/htmlspecialchars/

Upvotes: 0

Related Questions