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
- Place cursor on the word you want to replace
- Press
*— this searches for the exact word (with word boundaries) - Type
:%s//replacement/g— the empty pattern reuses the*search
Example
const userName = getUserName();
console.log(userName);
return userName;
With cursor on userName:
*searches for\<userName\>(whole word):%s//displayName/greplaces all occurrences
Why this is powerful
*adds word boundary anchors automatically, souserwon't matchuserName- The empty pattern
//in:salways reuses the last search - You can visually verify the matches (highlighted) before committing to the substitution
- Add
cflag 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/gpattern 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