How can I replace all camel case strings with kebab case strings in vscode with find and replace

Viewed 1060

I have a large collection of html files for a vue project that currently have inconsistent prop usage

some props are v-bind:prop-name="" some are v-bind:propName="" and some use the short hand :prop-name="" or :propName="".

and I would like to replace all props with the :prop-name="" syntax as per the vue docs.

I know that you can use regex in vscode (or a similar editor) to select only props with a camelCase format but im having a few issues.

for the find regex I cant figure out how to:

  1. select v-bind: or : as a prefix AND exclude it from a selection group
  2. split the camelCased string into selection groups
  3. dealing with propNameWithMoreThanTwoWords

for the replace syntax im pretty sure I have the right syntax :\L$1-$2=" from what I have found on other editors replace syntax but Id like some help on this too.

Totally ok with it being multiple passes to try get everything in the same format before the final update too.

im not adverse to using a different editor or somthing like a codemod (though I use windows)

1 Answers

To select all the strings that need modification use a RegEx Find

Find: ((?:v-bind)?:)([a-zA-Z0-9]+)([A-Z][a-z0-9]+)
Options: .* (RegEx)  Aa (Match Case)

Use menu option Selection | Select All Occurrences.

When you have all selected that you want to change (including v-bind and :) you can use the following keybinding to replace the variable names to kebab case

  {
    "key": "ctrl+shift+alt+f8", // or any other keybinding combo
    "command": "editor.action.insertSnippet",
    "args": {
      "snippet": "${TM_SELECTED_TEXT/([A-Z][a-z0-9_]+)/-${1:/downcase}/g}"
    },
    "when": "editorHasMultipleSelections && textInputFocus"
  }

A Find replace with the following Regex is also possible

Find: ((?:v-bind)?:)([a-zA-Z0-9]+)([A-Z][a-z0-9]+)
Replace: $1$2-\L$3
Options: .* (RegEx)  Aa (Match Case)

It can be used in Search Files Find-Replace.

You have to apply this Find-Replace multiple times, as many as there are Capital words in the variable with the most Capitals. The Find-Replace adjust the last Capital word of the variable name. Apply it again and it will adjust the now last Capital word. You can see in the Search Files if there are still conversions needed.

But for some reason VSC decides that capture group 3 are the last 2 characters of the variable name. If I test it on [regex101][1] (PCRE flavor to get `\L` recognised) the groups are captured correct, also if you select EcmaScript. `$3` should start with a capital and VSC also finds a hit on `:prop`

I filed an issue for this

Thanks to Mark who pointed me that I was bitten by the Match Case trap. In programming the default is Match Case but in VSC the default is Ignore Case

Related