Friday, April 29, 2011

Re: is there s 'toinitialupper' function?

On 04/29/2011 11:55 AM, Andrew Long wrote:
> I'm writing a script where I want to capitalise the first
> letter of a word. I know hat 'toupper' will change
> lower-to-upper case on the whole string, like \U in a :s
> command, but is there an equivalent of \u (convert the initial
> character only?)

I presume you want something like

let s = capitalise(s)

instead of doing a :s sort of command. While one doesn't exist,
you can use a mashup of the two:

let s=substitute(s, '\w\+', '\u\1', 'g')

if you just want to capitalize the first letter and leave the
rest alone. If you want to lowercase the rest, you can do

let s=substitute(s, '\(\w\)\(\w*\)', '\u\1\L\2', 'g')

The difference can be seen in transforming

let s = 'myVariable'

The first form will transform it to

MyVariable

while the second form will transform it to

Myvariable

And as always, if you want it functionized, you can easily wrap
it up:

function! Capitalize(s)
return substitute(s, '\(\w\)\(\w*\)', '\u\1\L\2', 'g')
endfunction

-tim


--
You received this message from the "vim_use" maillist.
Do not top-post! Type your reply below the text you are replying to.
For more information, visit http://www.vim.org/maillist.php

No comments:

Post a Comment