I know that rails automatically escapes characters like '<' or '&', but this does nothing for multiple spaces next to each other. I would like to escape everything, including spaces.
I understand that normally you don't want to use
and that you should use css instead. However, I'm trying to take user input and display it, so css isn't feasible.
For example, I have the user input: test
. When I display it with <%=@user_input%>
in the view, the extra whitespace is displayed as a single space (though it appears correctly in the source).
Is there an easy way to escape the whitespace? Should I just use h @user_input
and then replace all the spaces?
The whitespace isn't removed. Browsers simply interpret multiple whitespace characters as a single space.
You could convert each space to
if you want:
<%= raw @user_input.gsub(/\s/, " ") %>
You could alternatively replace each space with an empty <span class="whitespace"></span>
tag, and then use CSS to style the whitespace 'characters' however you like.
Finally, you can do this with only CSS too using the white-space: pre
style (example below).
Edit (to answer the follow-up in your comment)
<%= raw h("this is a sample & with ampersand.").gsub(/\s/, " ") %>
This escapes the &
as &
in the source (and will do similar for other HTML entities), and then does the " "
to
conversion.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With