Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove multiple spaces and new lines inside of String

Tags:

string

ruby

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. 
like image 420
Kreeki Avatar asked Aug 18 '11 11:08

Kreeki


People also ask

How do you get rid of extra spaces in a string?

Use JavaScript's string. replace() method with a regular expression to remove extra spaces. The dedicated RegEx to match any whitespace character is \s . Expand the whitespace selection from a single space to multiple using the \s+ RegEx.

How do you remove multiple spaces in a string in Python?

Using sting split() and join() You can also use the string split() and join() functions to remove multiple spaces from a string.

How do you delete multiple spaces with a single space in a string?

The metacharacter “\s” matches spaces and + indicates the occurrence of the spaces one or more times, therefore, the regular expression \S+ matches all the space characters (single or multiple). Therefore, to replace multiple spaces with a single space.

How do I remove multiple spaces from a string in Java?

To eliminate spaces at the beginning and at the end of the String, use String#trim() method. And then use your mytext. replaceAll("( )+", " ") .


2 Answers

check out Rails squish method:

http://apidock.com/rails/String/squish

like image 191
socjopata Avatar answered Oct 24 '22 04:10

socjopata


To illustrate Rubys built in squeeze:

string.gsub("\n", ' ').squeeze(' ') 
like image 36
steenslag Avatar answered Oct 24 '22 05:10

steenslag