How do I search backward for the word under the cursor?
Answer
#
Explanation
The # command searches backward for the exact word under the cursor, jumping to the previous occurrence. It is the counterpart to *, which searches forward.
How it works
#takes the word under the cursor and performs a whole-word backward search- It automatically wraps the word with
\<and\>word boundaries, so searching forthewill not matchthereorother - The search pattern is set in the search register, so you can press
Nto continue backward ornto go forward - All matches are highlighted if
hlsearchis enabled
Example
Given the text with the cursor on the last error:
if (error) {
log(error);
throw error;
}
Pressing # jumps the cursor backward to the error on the log(error) line. Pressing # again (or N) jumps to the first error in the if statement.
Tips
- Use
*to search forward for the word under the cursor instead - Use
g#to search backward without word boundaries (partial matches allowed) - After pressing
#, usento search forward (opposite direction) andNto continue backward (same direction) - Combine with
:%s//replacement/gto replace all occurrences — the search pattern from#is already set in the search register - Use
#Nto highlight all occurrences of the word without moving the cursor (search backward then jump back forward)