0

I need a function which strips the leading and trailing whitespaces from a string.

func! RemoveWhitespaces(String)
    ...
    return formattedString
endfunc

I was only able to find ways to substitute lines in buffer with their whitespaces stripped but this is not what I'm looking for.

How should I complete this function?

Bharath Hegde
  • 186
  • 1
  • 7

1 Answers1

0

My attempt:

func! RemoveWhitespaces(string)
    let string = a:string
    let result = substitute(string, '\s\+$', '', '')
    let result = substitute(string, '^\s\+', '', '')
    silent return result
endfunc

Now to get your result you can:

:let var=RemoveWhitespaces('  my string with spaces   ')
:echo var

update:

As romainl commentted, there is a easier way:

:let var=trim('   some text   ')
SergioAraujo
  • 11,069
  • 3
  • 50
  • 40