Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Remove Leading, Trailing and other consecutive white spaces in a string in RoR

    • 0
    • 1
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 812
    Comment on it

    There are innumerous ways to remove extra white spaces from a string in Ruby on Rails.

    Here i am demonstrating 3 ways which you can use to achieve the desired result.


    1> squish function :

    This function was introduced in Rails framework, this is not a Ruby function. It removes both the leading & trailing spaces & also removes the consecutive whitespaces in the string.
    Example:

     "             This is              for     testing squish  function        ".squish
    => "This is for testing squish function"
    

    2> Second way is to use the squeeze function in which we have passed a " "(space) as a parameter, it converts the consecutive whitespaces into a single space. And then the strip function is applied to the result which removes the leading & trailing white spaces.

    "      Thisssssssss is       Special    Text    for tesing           ".squeeze(" ").strip
    => "Thisssssssss is Special Text for tesing"
    

    3> Third way is to use the gsub method which does the same thing as done by squeeze method i.e removing the consecutive white spaces. It basically applies Regex to the specified string, then reurns the resultant string. And then the strip method removes the leading & trailing white spaces.

    "      Thisssssssss is     Special     Text    for tesing        ".gsub(/\s+/, " ").strip
    => "Thisssssssss is Special Text for tesing"
    

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: