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.
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.
Using sting split() and join() You can also use the string split() and join() functions to remove multiple spaces from 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.
To eliminate spaces at the beginning and at the end of the String, use String#trim() method. And then use your mytext. replaceAll("( )+", " ") .
check out Rails squish
method:
http://apidock.com/rails/String/squish
To illustrate Rubys built in squeeze:
string.gsub("\n", ' ').squeeze(' ')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With