'VSCode Snippet - Dynamically generating characters based on user input length [duplicate]

I have this basic snippet for vue-html

{
    "BANNER1": {
        "prefix": "banner",
        "body": ["<!-- ----------------", "/// $1", "--------------------- -->"]
    }
}

It render this

<!-- ----------------
/// ADD VALUES 
--------------------- -->

Right now, I hardcoded 16 dashes -

Can I dynamically generate the amount of - based on my $1?

Let's say, I enter "Hello" which contains 5 characters

I'm hoping to get this

<!-- -----
/// Hello
----- -->


Solution 1:[1]

Try this snippet:

"BANNER1": {
  "prefix": "banner",
  "body": [
    "<!-- ${1/./-/g}",
      "/// $1", 
      "${1/./-/g} -->"
  ]
}

{1/./-/g} will replace each character in $1 with a -. In that way you are effectively counting the number of characters in $1.

snippet length of input


What if you wanted to add one less than the length of $1, then use this:

"<!-- ${1/^.|(.)/${1:+-}/g}"

The first character, the . is not captured in a regex group. So if you wanted to use the length-2 you would change the first part to ^.. so ${1/^..|(.)/${1:+-}/g} or generically

${1/^.{n}|(.)/${1:+-}/g}

and replace that n with whatever number you want to subtract from the $1.

The rest of tabstop $1 is matched one by one (thanks to the global flag). And then the conditional

${1:+-} says if there was a capture group 1, then add a -. Capture group 1 itself is never added to the replacement.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1