ѕтƒ
ѕтƒ

Reputation: 3647

Appending white spaces to a string

I have a string:

str="Myname"

I want to add four white spaces after the string. What I did was:

str=str+"    "+"somename"

When I print the str as <%= str %>, the output shows only one white space. How can I make this work? I also tried:

str=str+" "*4+"somename"  

This also gives the same output as the one above gives. I don't want to print this. The string is used as a Ruby variable for more other operations. I can make it in Ruby, but not in RoR.

Upvotes: 2

Views: 8603

Answers (6)

Jeremiah
Jeremiah

Reputation: 81

<pre>I am a bad web programmer</pre>

pre tags of the bane of existence and should be avoided at all costs. Use this in your erb.

<%= raw(CGI.escapeHTML(str).gsub(/\s/, '&nbsp;')) %>

Upvotes: 0

aaron-coding
aaron-coding

Reputation: 2621

Following your same structure, it would be

str = raw(str + "&nbsp;&nbsp;&nbsp;&nbsp;" + "somename")

In HTML, only a single white space in counted, regardless of how many. So you must use the HTML Entity &nbsp; (means Non Breaking SPace) to show more than one space.

The raw part is required because Rails, by default, does not allow HTML Entities or any actual HTML to be output by strings, because they can be used by nefarious users to attack your site and/or users.

Therefore, you must use raw and also use &nbsp; in Rails.

Upvotes: 2

maximus ツ
maximus ツ

Reputation: 8065

you can replace the spaces with html encoding string and then render with html_safe or raw like,

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

Upvotes: 0

Muhamamd Awais
Muhamamd Awais

Reputation: 2385

if you try following code in console you will see that the issue is with your html;

str="Myname"
str=str+"    "+"somename"

=> "Myname    somename"

try it as follow

<pre>
  <%= str %>
</pre>

Upvotes: 0

Ankit
Ankit

Reputation: 1887

There may be 4 spaces in your variable but browser truncate the extra spaces after 1 space so you may not be viewing them. try following

<pre>
<%= str %>
</pre>

You will see spaces are added to your code. To achieve what you are trying to do put   rather then blank space

Upvotes: 0

harm
harm

Reputation: 10403

This has to do with how HTML handles whitespace. Which I assume you are using based on the Erb like syntax you used. If you really must output whitespace use &nbsp;.

But I suggest you try to fix this with CSS.

Upvotes: 5

Related Questions