skip to Main Content

In VScode I need one shortcut which can split one single string (camel-case) into words with space(s).
e.g.

getCheckoutCartHelper

desired output:

Get checkout cart helper

Tried to create shortcut in key-binding but nothing.

2

Answers


  1. There is a VS Code extension called "change-case". Install this extension. In VS Code, open the Shortcut settings with "Shift + Ctrl + P" and type in "Preferences: Open Keyboard Shortcuts". There you can search the command "extension.changeCase.sentence" and bind it to a shortcut.

    Regards

    Login or Signup to reply.
  2. It is worth pointing out that you can do this yourself, you don’t need to use an extension. You can parse and transform text with a snippet. Here is a snippet (inside a keybinding, in your keybindings.json):

    {
      "key": "alt+w",           // watever keybinding you want
      "command": "editor.action.insertSnippet",
      "args": {
    
        "snippet": "${TM_SELECTED_TEXT/^(.)|([A-Z])/${1:/capitalize}${2:+ }${2:/downcase}/gm}"
      },
      "when": "editorHasSelection"
    },
    

    The transform part ${1:/capitalize}${2:+ }${2:/downcase} capitalizes the first letter (capture group 1), then ${2:+ } is a conditional meaning if there is a capture group 2 add a space, then downcases all other capital letters (which are capture group 2s).

    It works on these two forms:

    getCheckoutCartHelper
    
    GetCheckoutCartHelper
    

    Note the use of the regex flags gm at the end of the transform. You want this to run multiple times, the first match will be the first letter in the selected text (and there will be no capture group 2 on the first match). Then other matches will have only capture group 2’s.

    transform camel case to Sentence case

    Now in your use case maybe it is simpler to use the extension but in the future you may want to be aware of this general alternative.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search