Search code examples
regexvisual-studio-codecode-snippets

Vscode snippet: tranform filename to Capitalize sentence with a regex


I want to tranform filename-with-dashes.md to Filename with dashes in a Vscode snippet

To be precise, I want to populate the field "title" in this snippet, from a filename similar to firt-post-ever.md and get First post ever:

"FrontMatter": {
    "scope": "markdown",
    "prefix": "frontmatter",
    "body": [
        "---",
        "title: '${TM_FILENAME_BASE/^([^-]*)-([^.]*).*/${1:/pascalcase} ${2:/capitalize}/}'",
        "draft: true",
[...]

What I have so far:

This regex changes filename-with-dashes.md to Filename with-dashes (← I still need to remove the dashes in the end):

${TM_FILENAME_BASE/^([^-]*)-([^.]*).*/${1:/pascalcase} ${2:/downcase}/}

Resources I checked:

Unfortunately, these pages wasn't enough to find a proper answer (I can't understand the regex syntax, despite heavy effort I can't get it..) Any hint?

Notes:

  • only the first letter of the whole title must be uppercase
  • the filename may contain dots (example: notes-for-dev.to-update-2022.md).
    In such case only the file extension must be stripped

Solution

  • Here is a snippet that works:

    "FrontMatter": {
        "scope": "markdown",
        "prefix": "frontmatter",
        "body": [
            "---",
            
            "title: '${TM_FILENAME_BASE/(^\\w*)|(-)/${1:/pascalcase}${2:+ }/g}'",
            
            // if other words might have caps you don't want
    
            "title: '${TM_FILENAME_BASE/(^\\w+)|(\\w+)|(-)/${1:/pascalcase}${3:+ }${2:/downcase}/g}'",
            
            "draft: true"
        ]
    }
    

    (^\\w+) get the first "word" in capture group 1
    (\\w+) get the any other words in capture group 2
    (-) get any - in capture group 3.

    ${1:/pascalcase} Capitalize the first letter of the first word and lowercase the rest of the letters of the first word.

    ${3:+ } If there is a group 3, add a space - thus replacing any -'s with spaces.