vimtricks.wiki Concise Vim tricks, one at a time.

How do I quickly replace all occurrences of the word under my cursor?

Answer

* then :%s//new/g

Explanation

Pressing * searches for the word under the cursor, which also loads it into the search register. You can then use :%s//new/g with an empty pattern — Vim automatically reuses the last search pattern. This two-step workflow is the fastest way to rename a word throughout a file.

How it works

  1. Place cursor on the word you want to replace
  2. Press * — this searches for the exact word (with word boundaries)
  3. Type :%s//replacement/g — the empty pattern reuses the * search

Example

const userName = getUserName();
console.log(userName);
return userName;

With cursor on userName:

  1. * searches for \<userName\> (whole word)
  2. :%s//displayName/g replaces all occurrences

Why this is powerful

  • * adds word boundary anchors automatically, so user won't match userName
  • The empty pattern // in :s always reuses the last search
  • You can visually verify the matches (highlighted) before committing to the substitution
  • Add c flag for confirmation: :%s//new/gc

Variations

" Use g* for partial match (no word boundaries)
g* then :%s//new/g

" Preview matches first
*       " Highlights all matches
n/N     " Navigate through matches to verify
:%s//new/gc  " Replace with confirmation

Tips

  • This pairs naturally with Vim's search highlighting (:set hlsearch)
  • The *:%s//replacement/g pattern is arguably the most efficient rename workflow in Vim
  • For multi-file rename, combine with :cdo: :vimgrep //g **/*.js | cdo s//new/g
  • # works like * but searches backward

Next

How do I always access my last yanked text regardless of deletes?