I am trying to make a keyboard shortcut in VS Code that will give me a random number from 1-100 when I use it.
This is currently the VS Code snippet I have. However, when I use it, it gives me the text that’s in the body.
Is it possible to make it give me a random number 1 to 100 instead?
"Print to console": {
"prefix": "makerandomnumber",
"body": [
"Math.floor(Math.random() * 100) + 1;"
],
"description": "Generate a random number"
}
2
Answers
A couple of thoughts: an extension I wrote can easily do what you want because it can run your javascript. Find and Transform.
Make this keybinding:
You’ll notice that is a keybinding and not a snippet (although I have done some work in "snippefying" the extension).
You can get close using vscode’s built-in snippet variables. See this snippet:
${RANDOM}
produces a 6-digit random number. The snippet then only uses the last 2 digits. I assume this would produce a number from 00-99, so perhaps not ideal for your use case.Here is a snippet that I think does close to what you want:
We can customize it further, as a previous answer noted, to only return 2 digits.
You can see that we can use a regex to capture the first two digits of the random 6 digit number that ${RANDOM} gives you and then we only return those first two captured digits.
(\d{2})
= captures the first two digits into regex group1.*
= captures the rest of the digits. ie. the last 4.$1
= Inserts regex group1 as the final output.To see what other variables you can use in VSCode snippets see reference:
https://code.visualstudio.com/docs/editor/userdefinedsnippets#_variables
Note: You can not use javascript in the snippet body.
reference: https://code.visualstudio.com/docs/editor/userdefinedsnippets