Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to escape whitepace in Rails?

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 &nbsp; 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?

like image 374
Cassie Avatar asked Feb 19 '23 17:02

Cassie


1 Answers

The whitespace isn't removed. Browsers simply interpret multiple whitespace characters as a single space.

You could convert each space to &nbsp; if you want:

<%= raw @user_input.gsub(/\s/, "&nbsp;") %>

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).

  • http://jsfiddle.net/G3VnY/

Edit (to answer the follow-up in your comment)

<%= raw h("this      is      a    sample   &  with   ampersand.").gsub(/\s/, "&nbsp;") %>

This escapes the & as &amp; in the source (and will do similar for other HTML entities), and then does the " " to &nbsp; conversion.

like image 165
deefour Avatar answered Mar 03 '23 13:03

deefour