Reverse a word in Vim

Here is another (pythonic) solution based on how this works:

:echo join(reverse(split('hello', '.\zs')), '')
olleh

If you want to replace all words in the buffer,

:%s/\(\<.\{-}\>\)/\=join(reverse(split(submatch(1), '.\zs')), '')/g

This works by first creating a list of characters in the word, which is reversed and joined back to form the word. The substitute command finds each word and then passes the word to the expressions and uses the result as replacement.


This Tip might help: http://vim.wikia.com/wiki/Reverse_letters

It says:

Simply enable visual mode (v), highlight the characters you want inverted, and hit \is. For a single word you can use vw (or viw): viw\is

vnoremap <silent> <Leader>is :<C-U>let old_reg_a=@a<CR>
 \:let old_reg=@"<CR>
 \gv"ay
 \:let @a=substitute(@a, '.\(.*\)\@=',
 \ '\=@a[strlen(submatch(1))]', 'g')<CR>
 \gvc<C-R>a<Esc>
 \:let @a=old_reg_a<CR>
 \:let @"=old_reg<CR>

There are more solutions in the comments.

Tags:

Python

Vim

Regex