Search code examples
visual-studio-codevscode-snippets

VS Code Snippets: How to replace underscore with spaces and capitalize words


I can replace underscores with spaces from the $1 like this ${1/[_]/ /g}

And the capitalization is done with ${1/(.*)/${1:/capitalize}/}

But how to combine both to get a result like this:

model_name --> Model Name?


Solution

  • Try:

    "${1/([^_]*)(_?)/${1:/capitalize}${2:+ }/g}"

    That will capture everything before an underscore in group 1 and capitalize that group.

    The underscore, if any, will be in capture group 2. ${2:+ } is a conditional: if there is a capture group 2, add a space.

    Note the global g at the end is necessary to repeatedly match each of these groups along the input.

    It will work with any length input from:

    model
    model_name
    model_name_more_stuff    // etc.