skip to Main Content

I’m trying to write a code snippet to capitalize each word in the filename base where the words are separated by dashes. While I know the words in the filename base will be separated by dashes, I don’t know how may words to expect in the filename base. There could be zero or more dashes in my filename base. So, I could have:

name.extension
some-file-name.extension
yet-another-file-name.extension
and-yet-even-another-file-name.extension

etc., and I’d like these to become

Some File Name
Yet Another File Name
And Yet Even Another File Name

etc., respectively, in my code.

I’ve tried in an attempt just to get the first word to capitalize, but this only drops the first letter of my filename base, and leaves the rest unchanged:

${TM_FILENAME_BASE/[\w+]/${1:/capitalize}/}

What am I missing? How do I iterate with the snippets syntax?

2

Answers


  1. Chosen as BEST ANSWER

    I managed to get this to work with the following, but I don't understand why it works. Please edit this response if you can help out.

    This will return the desired string:

    ${TM_FILENAME_BASE/(\w+)|(\W+)/${1:/capitalize}${2:+ }/g}

    Explanation:

    • TM_FILENAME_BASE is a Code snippets variable. It doesn't include the extension, so we don't need to worry about writing a regex expression to get rid of that; we get to start with (e.g.) some-file-name.
    • (\w+)|(\W+) defines two regex search groups:
      • (\w+) returns any group of alphanumeric text
      • (\W+) returns any group of non-alphanumeric text
    • ${1:/capitalize}${2:+ }/g capitalizes the first group, and if it finds a second group will remove and replace the dashes with a space. The final /g switch makes the entire expression greedy.

    Here's the bit I don't get: I don't understand why I need the + in ${2:+ }. If I use ${2: }, though (no +), the return value comes out as Some -File -Name (note also final trailing space in addition to the other unexpected aspects of the return value).


  2. If you use the following body it works

    • a literal . and extension => ignore
    • catch a possible - followed by text until a . or -
    • substitute the - by a space and capitalize the word
    "body": "${TM_FILENAME_BASE/(\.\w+$)|(-?)([^-.]+)/${2:+ }${3:/capitalize}/g}"
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search