Home > other >  In VSCode snippets how do you use transform to lowercase just the first letter of a value?
In VSCode snippets how do you use transform to lowercase just the first letter of a value?

Time:09-24

I've just started getting into vsCode snippets. They seem really handy.

Is there a way to ensure that what a user entered at a tabstop starts with a lowercase value.

Here's my test case/ sandbox :

 "junk": {
    "prefix": "junk",
    "body": [
      "original:${1:type some string here then tab}",
      "lower:${1/(.*)/${1:/downcase}/}",
      "upper:${1/(.*)/${1:/upcase}/}",
      "capitalized:${1/(.*)/${1:/capitalize}/}",
      "camel:${1/(.*)/${1:/camelcase}/}",
      "pascal:${1/(.*)/${1:/pascalcase}/}",
    ],
    "description": "junk"
  }

and here's what it produces:

original:SomeValue
lower:somevalue
upper:SOMEVALUE
capitalized:SomeValue
camel:somevalue
pascal:Somevalue

"camel" is pretty close but I want to preserve the capital if the user entered a camelcase value.

I just want the first character lower no matter what.

CodePudding user response:

The answer is:

${1/(.)(.*)/${1:/downcase}$2/}

CodePudding user response:

Just to clarify, if you look at this commit: https://github.com/microsoft/vscode/commit/3d6389bb336b8ca9b12bc1e772f7056d5c03d3ee

function _toCamelCase(value: string): string {
        const match = value.match(/[a-z0-9] /gi);
  console.log(match)
        if (!match) {
            return value;
        }
        return match.map((word, index) => {
            if (index === 0) {
                return word.toLowerCase();
            } else {
                return word.charAt(0).toUpperCase()
                      word.substr(1).toLowerCase();
            }
        })
            .join('');
    }

the camelcase transform is intended for input like

some-value
some_value
some.value

I think any non [a-z0-9]/i will work as the separator between words. So your case of SomeValue is not the intended use of camelcase: according to the function above the entire SomeValue is one match (the match is case-insensitve) and then that entire word is lowercased.

  • Related