Last updated: Apr 6, 2024
Reading time·3 min
To rename a variable in Visual Studio Code:
F2
.Enter
.All occurrences of the variable will be renamed, across all files.
If you are on macOS and the F2
keyboard shortcut doesn't work, use Fn
+
⌘
+ F2
or just Fn
+ F2
.
The command won't replace text that contains the name of the variable.
Notice that the my site
string didn't get replaced in the example.
You don't have to select the variable's declaration to rename it. You can select
any of its occurrences and press F2
.
You can also use the rename symbol command using the Command Palette:
Click on the variable.
Press:
Ctrl
+ Shift
+ P
on Windows and Linux.Command
+ Shift
+ P
on macOS.F1
to open the Command Palette.You can also right-click on a variable and select Rename Symbol from the menu.
There is also a Ctrl
+ F2
(or Cmd
+ F2
) keyboard shortcut that allows
you to select all occurrences of the current word.
However, this doesn't only select variables.
It also selects strings that contain the name of the variable or parts of other variables that contain the specified text.
The Ctrl
+ F2
keyboard shortcut is limited to the currently opened file.
On the other hand, the rename symbol action works across files.
When you use the F2
(rename symbol) command, note:
If the variable is only referenced in a single file, VS Code only renames the variable in the single file.
If the variable is referenced in multiple files, VS Code makes changes to all of the files in the project that reference the variable.
VS Code is smart, so it doesn't just blindly rename other variables with the same name. Instead, it looks for references to the same variable.
You might not want to rename the variables across all files or you might not want to rename all occurrences of the variable in the file.
VS Code's rename symbol functionality allows you to preview the changes and selectively rename a variable.
Click on the variable.
Press F2
.
Type the new name of the variable.
Press Shift
+ Enter
to preview the changes.
Once you press Shift
+ Enter
a refactor preview window opens at the bottom.
You can uncheck the checkbox to not rename specific instances of the variable.
You can also uncheck the checkbox to not rename instances of the variable in a specific file.
Once you select the instances which you want to rename, click on the Apply button.
Here is a short clip that demonstrates the process of renaming a variable selectively.
Notice that I unchecked the checkbox next to another.js
, so the variable
doesn't get renamed in the specified file.
All of the entries are checked by default, so you can also use the feature to simply preview the changes.
The rename symbol functionality can also be used to rename a tag:
F2
.Enter
.The opening and the corresponding closing tags get renamed automatically.
I've also written a guide on how to rename a file, folder or workspace in VS Code.
You can learn more about the related topics by checking out the following tutorials: