Spaces are not removed. Browsers simply interpret multiple whitespace as a single space.
You can convert each space to , if you want to:
<%= raw @user_input.gsub(/\s/, " ") %>
Instead, you can replace each space with an empty <span class="whitespace"></span> , and then use CSS for the space character styles as you like.
Finally, you can do this with CSS only , using the white-space: pre style (example below).
Edit (to respond to a subsequent comment in your comment)
<%= raw h("this is a sample & with ampersand.").gsub(/\s/, " ") %>
It speeds up & like & in the source (and will be similar for other HTML objects) and then converts the " " to .
source share