Search code examples
visual-studio-codevscode-snippets

Perform replace operation on selected (highlighted) string


In visual code, let say I have a string:

I need this feature urgently!

When I select the text "urgently" and press Cntrl + 1, then visual code will change the selected string as such:

I need this feature <span class="warn">urgently</span>!

Is it possible in visual code?


Solution

  • You can do that easily with a snippet. Put this into your keybindings.json:

    {
        "key": "ctrl+k ctrl+1",
        "command": "editor.action.insertSnippet",
          "args": {
            "snippet": "<span class=\"warn\">$TM_SELECTED_TEXT</span>",
        }
    },
    

    I used Ctrl+K Ctrl+1 as the keybinding because Ctrl+1 already is bound to the focus first editor group command, but you may or may not care keeping that functionality.

    If you really want to use Ctrl+1 as your snippet's keybinding, put this into your keybindings.json:

    {
        "key": "ctrl+1",
        "command": "editor.action.insertSnippet",
          "args": {
            "snippet": "<span class=\"warn\">$TM_SELECTED_TEXT</span>",
        }
    },
    {
      "key": "ctrl+1",
      "command": "-workbench.action.focusFirstEditorGroup"
    },
    

    The - before -workbench.action.focusFirstEditorGroup removes that keybinding.