英文:
How can I create a VS Code keyboard shortcut to change a camel-case string to sentence-case?
问题
在VScode中,我需要一个快捷键,可以将一个单一的字符串(驼峰命名)分割成用空格分隔的单词。
例如:
getCheckoutCartHelper
期望的输出:
Get checkout cart helper
尝试在键绑定中创建快捷方式,但没有成功。
英文:
In VScode I need one shortcut which can split one single string (camel-case) into words with space(s).
e.g.
getCheckoutCartHelper
desired output:
Get checkout cart helper
Tried to create shortcut in key-binding but nothing.
答案1
得分: 3
这里有一段关于文本转换的说明,以及一个代码段示例,它可以将驼峰命名的文本转换为句子格式的文本。你可以使用这个代码段,无需使用扩展插件。
以下是代码段示例(在你的 keybindings.json
中的一个键绑定内):
{
"key": "alt+w", // 你想要的快捷键
"command": "editor.action.insertSnippet",
"args": {
"snippet": "${TM_SELECTED_TEXT/^(.)|([A-Z])/${1:/capitalize}${2:+ }${2:/downcase}/gm}"
},
"when": "editorHasSelection"
}
${1:/capitalize}${2:+ }${2:/downcase}
部分是用来转换文本的。它首字母大写(捕获组 1),然后 ${2:+ }
是一个条件,意思是如果存在捕获组 2,就添加一个空格,然后将所有其他大写字母转换为小写(它们是捕获组 2)。
这段代码适用于以下两种形式的文本:
getCheckoutCartHelper
GetCheckoutCartHelper
请注意,在转换的末尾使用了正则表达式标志 gm
。这是因为你希望它多次运行,第一个匹配将是所选文本的第一个字母(第一个捕获组没有第二个捕获组)。然后其他匹配将只有捕获组 2。
现在在你的使用情况下,也许使用扩展插件更简单,但在将来,你可能会想了解这个通用的替代方法。
英文:
It is worth pointing out that you can do this yourself, you don't need to use an extension. You can parse and transform text with a snippet. Here is a snippet (inside a keybinding, in your keybindings.json
):
{
"key": "alt+w", // watever keybinding you want
"command": "editor.action.insertSnippet",
"args": {
"snippet": "${TM_SELECTED_TEXT/^(.)|([A-Z])/${1:/capitalize}${2:+ }${2:/downcase}/gm}"
},
"when": "editorHasSelection"
},
The transform part ${1:/capitalize}${2:+ }${2:/downcase}
capitalizes the first letter (capture group 1), then ${2:+ }
is a conditional meaning if there is a capture group 2 add a space, then downcases all other capital letters (which are capture group 2s).
It works on these two forms:
getCheckoutCartHelper
GetCheckoutCartHelper
Note the use of the regex flags gm
at the end of the transform. You want this to run multiple times, the first match will be the first letter in the selected text (and there will be no capture group 2 on the first match). Then other matches will have only capture group 2's.
Now in your use case maybe it is simpler to use the extension but in the future you may want to be aware of this general alternative.
答案2
得分: 2
有一个名为“change-case”的VS Code扩展。安装此扩展。在VS Code中,使用“Shift + Ctrl + P”打开快捷键设置,然后键入“Preferences: Open Keyboard Shortcuts”。在那里,您可以搜索命令“extension.changeCase.sentence”并将其绑定到快捷键。
致敬
英文:
There is a VS Code extension called "change-case". Install this extension. In VS Code, open the Shortcut settings with "Shift + Ctrl + P" and type in "Preferences: Open Keyboard Shortcuts". There you can search the command "extension.changeCase.sentence" and bind it to a shortcut.
Regards
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论