Search code examples
visual-studio-codecode-snippetsvscode-snippets

How to capitalise a letter in a custom snippet?


I am trying to create a snippet using vs code (javascript.json) to do the following code.

const [click, setClick] = useState(false)

I have created the following snippet which sort of works.

    "My Custom useState": {
    "prefix": "myus",
    "body": [
        "const [${1:name}, set${1:name}] = useState(${2|true,false|})"
    ],
    "description": "My Custom useState"
}

But in the example, I want to try and find a way to capitalise the second word. So the above snippet output is

const [click, setclick] = useState(false)

Currently, I go back into the code and change to a capital letter by hand, but it has reduced the amount of code I write.


Solution

  • Try this as the body:

    "const [${1:name}, set${1/(.)/${1:/capitalize}/}] = useState(${2|true,false|})"

    That will "transform" the first letter (.) of that capture group 1 into a capital letter ${1:/capitalize}.

    In your case ${1:/upcase} would do the same thing since the capture group only contains the first letter. Normally, ${1:/upcase} will capitalize the entire capture group, not just the first letter like ${1:/capitalize} does.

    What will not work is set${1:name/(.)/${1:/capitalize}/} where the default :name is used. You cannot transform a default. See https://github.com/microsoft/vscode/issues/56703