I'm writing a snippet in which I need to get the current file name in vimscript. I can do this happily with expand('%:t:r')
(as shown here). However, I'd like to not only exclude '.js' from the filename, but also '.test'.
e.g.
If in myName.test.js
, I would like to grab 'myName'
If in myName.js
, I would also like to grab 'myName'
I'm doing this to create an UltiSnips snippet so other methods (e.g. regex) would also be useful
The :t
and :r
are filename modifiers. If you follow :help filename-modifiers
, there's also a nifty (but little known) :s?pat?sub?
modifier that can perform substitutions. As this can be combined with the other modifiers, all you need to do is match .test
anchored to the end of the filename:
:echo expand('%:t:r:s?\.test$??')
There's no error if the substitution fails, so there's no need to make the match optional (via \?
).