DEV Community

Stephen Chiang
Stephen Chiang

Posted on • Updated on

Quick VS Code refactor/productivity trick

So I was browsing Dev.to , like I normally do while waiting for my build process to finish (๐Ÿฑโ€๐Ÿ‘ค) and I saw this post:

And I thought I would share my one of my favorites.

Often when I need to create an object and as a test or have common values except for a single character I use this flow. It also works in refactoring just pieces of code really fast.

demo

Here's an example, let's say i have an array of objects where I want the values to be 'test1', 'test2', 'test3' respectively to each object in the array:

const test = 'test';

const objectArray = [
      {
        prop1: 'test`,
        prop1: 'test`,
        prop1: 'test`,
        prop1: 'test`,
      },
      {
        prop1: 'test`,
        prop1: 'test`,
        prop1: 'test`,
        prop1: 'test`,
      },
      {
        prop1: 'test`,
        prop1: 'test`,
        prop1: 'test`,
        prop1: 'test`,
      },
      ];
Enter fullscreen mode Exit fullscreen mode

In this case you could just use a multi-cursor and type in the numerical value at the end, but here's another way that that helps out when it's not so easy.

You could use the ctr + h to replace test with test1, but that could replace more than what you had intended, like the string variable called test above objArray.

So here's what I do:

  1. Select the block of code using some combination of shift, ctrl and arrow keys that is most appropriate.
  2. alt + l (this notifies vs code that you intend to only do this operation on the selected block.
  3. ctrl + h (opens the find/replace dialog box)
  4. type in the value to be replaced
  5. tab over to type in the value to be replaced
  6. ctrl + enter. *update: new version of VS Code defaults to ctrl + alt + enter but can be changed back in they keyboard shortcuts
  7. repeat for the next block

๐Ÿ”ฅFor me, this is quite fast once the pattern becomes natural.

Voilaโ— now it should look like the following:

const test = 'test';

const objectArray = [
      {
        prop1: 'test1`,
        prop1: 'test1`,
        prop1: 'test1`,
        prop1: 'test1`,
      },
      {
        prop1: 'test2`,
        prop1: 'test2`,
        prop1: 'test2,
        prop1: 'test2,
      },
      {
        prop1: 'test3`,
        prop1: 'test3`,
        prop1: 'test3`,
        prop1: 'test3`,
      },
      ]
Enter fullscreen mode Exit fullscreen mode

And your fingers never had to leave the keyboard, cheers! ๐Ÿป

If you find this valuable, please leave a comment and follow me on Dev.to @chiangs and Twitter @chiangse, ๐Ÿป cheers!

Top comments (0)