Kreeki
Kreeki

Reputation: 3732

Remove multiple spaces and new lines inside of String

Suppose we have string like this:

Hello, my\n       name is Michael.

How can I remove that new line and strip those spaces after that into one inside of string to get this?

Hello, my name is Michael.

Upvotes: 116

Views: 78015

Answers (9)

socjopata
socjopata

Reputation: 5095

check out Rails squish method:

https://api.rubyonrails.org/classes/String.html#method-i-squish

Upvotes: 213

Convincible
Convincible

Reputation: 341

You can add just the squish method (and nothing else) to Ruby by including just this Ruby Facet:

https://github.com/rubyworks/facets/blob/master/lib/core/facets/string/squish.rb

require 'facets/string/squish'

Then use

"my    \n   string".squish #=> "my string"

Doesn't require Rails.

Upvotes: 2

vikas pal
vikas pal

Reputation: 75

Use squish
currency = " XCD"
str = currency.squish
 str = "XCD" #=> "XCD"

Upvotes: 3

anusha
anusha

Reputation: 2135

Try This:

s = "Hello, my\n       name is Michael."
s.gsub(/\n\s+/, " ")

Upvotes: 16

steenslag
steenslag

Reputation: 80065

To illustrate Rubys built in squeeze:

string.gsub("\n", ' ').squeeze(' ')

Upvotes: 43

Ali
Ali

Reputation: 12674

this regex will replace instance of 1 or more white spaces with 1 white space, p.s \s will replace all white space characters which includes \s\t\r\n\f:

a_string.gsub!(/\s+/, ' ')

Similarly for only carriage return

str.gsub!(/\n/, " ")

First replace all \n with white space, then use the remove multiple white space regex.

Upvotes: 6

fl00r
fl00r

Reputation: 83680

my_string = "Hello, my\n       name is Michael."
my_string = my_string.gsub( /\s+/, " " )

Upvotes: 8

Nikola
Nikola

Reputation: 704

Use String#gsub:

s = "Hello, my\n       name is Michael."
s.gsub(/\s+/, " ")

Upvotes: 4

Koraktor
Koraktor

Reputation: 42903

The simplest way would probably be

s = "Hello, my\n       name is Michael."
s.split.join(' ') #=> "Hello, my name is Michael."

Upvotes: 24

Related Questions