Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is there a vimscript equivalent for Ruby's strip() (strip leading and trailing spaces)?

Tags:

vim

I'm looking for a VimScript function that strips any trailing or leading spaces before a string.

like image 565
dan Avatar asked Dec 18 '10 16:12

dan


2 Answers

Since 8.0.1630 vim has trim().

For older version: assuming you're trying to do this on a variable in vimscript, you can do this:

let new_var = substitute(var, '^\s*\(.\{-}\)\s*$', '\1', '')

You could always make you're own function if you like:

function! Strip(input_string)
    return substitute(a:input_string, '^\s*\(.\{-}\)\s*$', '\1', '')
endfunction

let new_var = Strip(var)
like image 178
DrAl Avatar answered Nov 09 '22 17:11

DrAl


Since 8.0.1630 vim has a built-in trim() function to do this. From the docs:

trim({text}[, {mask}])

  Return {text} as a String where any character in {mask} is
  removed from the beginning and  end of {text}.
  If {mask} is not given, {mask} is all characters up to 0x20,
  which includes Tab, space, NL and CR, plus the non-breaking
  space character 0xa0.
  This code deals with multibyte characters properly.

So, calling trim(var) will strip leading and trailing whitespace from var.

like image 37
m-pilia Avatar answered Nov 09 '22 18:11

m-pilia