Search code examples
javascriptregexvscode-snippets

Remove the extension of filename and convert camelCase to snake case using regex vscode snippets?


I need to create many files on same structure. The modules exported and filename have some relation. I have to convert. Example input and outputs.

startNewGame.ts => start-new-game
gameOver.ts => game-over
ALongNameForAFile.ts=> a-long-name-for-file
short.ts => short

My current regex is

${TM_FILENAME/([A-Z])/-${1:/downcase}/g}

For now I am only able to remove change capital letter so small and add -. There are two problems

  • I am unable to remove .ts
  • There is extra - in the start.

Note: I am using this in vscode snippets


Solution

  • You were close on removing the file name extension: use TM_FILENAME_BASE instead. See vscode snippet variables.

    "filename change": {
      "prefix": "_co",
      "body": [
        "${TM_FILENAME_BASE/(^[A-Z])|([A-Z])/${2:+-}${2:/downcase}${1:/downcase}/g}",
      ],
      "description": ""
    },
    

    Since the leading - only happens when there is a capital letter at the start, I found it easiest to handle that case separately. So the regex is now:

    (^[A-Z])|([A-Z]) // the order is important.

    ${2:+-} is a conditional, add the - only if there is a capture group 2.