开发者

Escaping ampersands input by users through text fields?

开发者 https://www.devze.com 2022-12-08 13:05 出处:网络
Like almost all apps today, I have users who enter various information through standard text inputs.My app is running on Rails.

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

精彩评论

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