25

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

dan
  • 43,914
  • 47
  • 153
  • 254

2 Answers2

35

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)
alkino
  • 760
  • 6
  • 15
DrAl
  • 70,428
  • 10
  • 106
  • 108
  • 1
    I used to write this as `substitute(str, '^\s\+\|\s\+$', '', 'g')`. It is surprising, but your variant works a bit faster. – ZyX Dec 18 '10 at 23:23
  • 2
    @Zyx: I think my variant is faster because it's always anchored to the start of the line, so the parser doesn't have to try to match from every single character (this also means it doesn't need the 'g' flag to make it keep trying). – DrAl Dec 21 '10 at 14:07
  • 1
    `\v` ftw: `substitute(var,'\v^\s*(.{-})\s*$','\1','')` – jthill May 11 '15 at 16:54
  • 1
    You might want to use `\_s` instead of `\s` to handle new lines as well. That is the default behaviour of `trim()` – Cimbali Oct 23 '19 at 11:31
  • how should i read the ^\s... expression, i am attempting to strip a leading character – Fuseteam Apr 22 '20 at 05:05
  • With my function, just in case `trim()` turned out to be much faster than the substitution, I also added `if has('nvim') || v:versionlong >= 8001630` to use trim(), otherwise I use the substitution. – Will Eccles Jul 23 '20 at 14:00
20

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.

From version 8.2.0868, a third optional argument allows to specify whether to trim from begin, end, or both:

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

 The optional {dir} argument specifies where to remove the
 characters:
     0   remove from the beginning and end of {text}
     1   remove only at the beginning of {text}
     2   remove only at the end of {text}
 When omitted both ends are trimmed.

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

m-pilia
  • 526
  • 4
  • 6