• RSS
  • Delicious
  • Digg
  • Facebook
  • Twitter
  • Linkedin
  • Youtube

converting all newline characters to br tag

I was surprised as there is no function in ruby to convert all newline characters to <br>.

Here is a php nl2br equivalent method to convert all newline characters (\n) to break tag (<br>) in a string.

 def nl2br(s)
s.gsub(/\\n/, '<br>')
end

5 Responses so far.

  1. Pratik says:

    def nl2br(s)
    s.gsub(/\n/, ”)
    end

    This would be more appropriate :)

  2. Akhil Bansal says:

    This will remove all new line characters not replace them by &lt;br&gt; :-)

  3. Stian says:

    I believe he was reffering to the /\n/ part. Since /n/ will remove all n-characthers and replace them with :P

  4. Nadeem Yasin says:

    for development in rails, just use simple_format(str) function.
    Its really simple..


Asset Pipeline has been extracted a...

The asset pipeline which was introduced in Rails 3.1, has ...

ClientSideValidations: Add/Map mode...

#/status/256699237230845952

Action and Page caching has been ex...

With the commit c82cf81f00f Action and Page caching has been extracted ...

turbo-sprockets-rails3: Speeds up ...

#/status/253420357841723393

EdgeRails: ActiveRecord::SessionSto...

With the commit 3324e28804 ActiveRecord::SessionStore is extracted out of Rails into ...

Asset Pipeline has been extracted a...

The asset pipeline which was introduced in Rails 3.1, has ...

ClientSideValidations: Add/Map mode...

#/status/256699237230845952

Action and Page caching has been ex...

With the commit c82cf81f00f Action and Page caching has been extracted ...

turbo-sprockets-rails3: Speeds up ...

#/status/253420357841723393

EdgeRails: ActiveRecord::SessionSto...

With the commit 3324e28804 ActiveRecord::SessionStore is extracted out of Rails into ...