开发者

Escaping ampersands input by users through text fields?

Like almost all apps today, I have users who enter various information through standard text inputs. My app is running on Rails.

It's a no-brainer to escape ampersands that I include as part of the site copy, etc. But how do I escape an ampersand that is dynamically input by a user? Currently, it开发者_C百科's breaking my frontend validation.


When you display the values you need to replace certain characters with HTML entities. Those characters are:

& : &
< : &lt;
> : &gt;
" : &quot;

Perhaps there is a HtmlEncode function that you can use for that, otherwise you can use plain string operations. Pseudo code:

output replace(replace(replace(replace(text, "&", "&amp"), "<", "&lt;"), ">", "&gt;", """", "&quot;")

Edit:
I found that you can use the html_escape() function:

<%=html_escape @text%>

Or short:

<%=h @text%>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜