javascriptvisual-studio-codevscode-snippets

How to wrap a line in console.log


I find myself frequetly wanting to enclose statements or lines with a console.log(...). For example if I have the following code:

let myVar = "Hello";
myVar.slice(1,3);|            // '|' means where the cursor is after typing in the last line

And from there I'd like to wrap that line in a console.log so it then becomes:

let myVar = "Hello";
console.log(myVar.slice(1,3));

Is there a short-cut that I can create in VS Code to do this? I have one extension that is supposed to do this but 80% of the time it gets it wrong (for example putting the ) after the ; and so I'd just like to do one short-cut command that always gets it right, without having to install an extension. How could I do this?


Solution

  • Put this into your keybindings.json:

    {
      "key": "alt+q",
      "command": "runCommands",
      "args": {
        "commands": [
          "cursorHomeSelect",
          {
            "command": "editor.action.insertSnippet",
            "args": {
              "snippet": "${TM_SELECTED_TEXT/(.*)./console.log($1);/}"
            }
          }
        ]
      },
      "when": "editorFocus"
    }
    

    That uses the newer built-in command runCommands which itself can run multiple commands in a keybinding.

    cursorHomeSelect first to select from the cursor to beginning of text on line.

    (.*). Capture the rest of the line except for the last character ;. That last matched ; will not be in capture group 1 and so will not appear within the console.log...) body.