Search code examples
regexvisual-studio-codevscode-snippets

vscode snippet - transform and replace filename


my filename is

some-fancy-ui.component.html

I want to use a vscode snippet to transform it to

SOME_FANCY_UI

So basically

  1. apply upcase to each character
  2. Replace all - with _
  3. Remove .component.html

Currently I have

'${TM_FILENAME/(.)(-)(.)/${1:/upcase}${2:/_}${3:/upcase}/g}'

which gives me this

'SETUP-PRINTER-SERVER-LIST.COMPONENT.HTML'

The docs doesn't explain how to apply replace in combination with their transforms on regex groups.


Solution

  • If the chunks you need to upper are separated with - or . you may use

    "Filename to UPPER_SNAKE_CASE": {
        "prefix": "usc_",
        "body": [
            "${TM_FILENAME/\\.component\\.html$|(^|[-.])([^-.]+)/${1:+_}${2:/upcase}/g}"
        ],
        "description": "Convert filename to UPPER_SNAKE_CASE dropping .component.html at the end"
    }
    

    You may check the regex workings here.

    • \.component\.html$ - matches .component.html at the end of the string
    • | - or
    • (^|[-.]) capture start of string or - / . into Group 1
    • ([^-.]+) capture any 1+ chars other than - and . into Group 2.

    The ${1:+_}${2:/upcase} replacement means:

    • ${1:+ - if Group 1 is not empty,
    • _ - replace with _
    • } - end of the first group handling
    • ${2:/upcase} - put the uppered Group 2 value back.