将 VSCode 用户代码段转换为蛇形大小写 [英] VSCode user snippet to convert to snake case

查看:64
本文介绍了将 VSCode 用户代码段转换为蛇形大小写的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是的,我知道这是当前的功能.我要找一个朋友 (Azure Data Studio).

我需要一个用户代码段,将 Camel Case 或 Pascal Case(突出显示)字符串转换为较低的 Snake Case.我在这里改编了

现在它在末尾添加了一个额外的 _ ,您可以将其退格或将其放入为您执行此操作的宏中.这里使用multi-command:

<代码>{key":alt+enter",任何你想要的键绑定命令":extension.multiCommand.execute",参数":{序列":[{命令":editor.action.insertSnippet",参数":{片段":${TM_SELECTED_TEXT/([AZ]{2,})(?=[AZ][az]+[0-9]*|$)|([AZ]?[az]+[0-9]*|[AZ]|[0-9]+)([- _])?/${1:/downcase}${2:/downcase}_/gm}"},},删除左"]},何时":editorTextFocus &&"editorHasSelection"}

Yep, I'm aware this is current functionality. I'm asking for a friend (Azure Data Studio).

I need a user snippet that will convert either Camel Case or Pascal Case (highlighted) strings to lower Snake Case. I adapted this answer here which gets me close but it can't handle a sequence of Upper Case letters e.g. HTML.

"snake":{
    "prefix": "snake",
    "body": "${TM_SELECTED_TEXT/(^[A-Z][a-z]*|[a-z])([A-Z])?/${1:/downcase}${2:+_}${2:/downcase}/g}"
}

Ideally I could get results like

Converts a string to snake case.

  • Use String.prototype.match() to break the string into words using an appropriate regexp.
  • Use Array.prototype.map(), Array.prototype.slice(), Array.prototype.join() and String.prototype.toLowerCase() to combine them, adding _ as a separator.

const toSnakeCase = str =>
  str &&
  str
    .match(/[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+/g)
    .map(x => x.toLowerCase())
    .join('_');


toSnakeCase('camelCase'); // 'camel_case'
toSnakeCase('some text'); // 'some_text'
toSnakeCase('some-mixed_string With spaces_underscores-and-hyphens'); // 'some_mixed_string_with_spaces_underscores_and_hyphens'
toSnakeCase('AllThe-small Things'); // 'all_the_small_things'
toKebabCase('IAmEditingSomeXMLAndHTML');

from 30 seconds of code: convert to snake_case

解决方案

Try this (I converted the regex from your second link):

"snake": {
  "prefix": "snake",
  "body": "${TM_SELECTED_TEXT/([A-Z]{2,})(?=[A-Z][a-z]+[0-9]*|$)|([A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+)([- _])?/${1:/downcase}${2:/downcase}${2:+_}/gm}"
},

Right now it adds an extra _ at the end which you could just backspace over or put it into a macro that does that for you. Here using multi-command:

{
  "key": "alt+enter",             whatever keybinding you want
  "command": "extension.multiCommand.execute",
  "args": {
    "sequence": [
      {
        "command": "editor.action.insertSnippet",
        "args": {
          "snippet": "${TM_SELECTED_TEXT/([A-Z]{2,})(?=[A-Z][a-z]+[0-9]*|$)|([A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+)([- _])?/${1:/downcase}${2:/downcase}_/gm}"
        },
      },
      "deleteLeft"
    ]
  },
  "when": "editorTextFocus && editorHasSelection"
}

这篇关于将 VSCode 用户代码段转换为蛇形大小写的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆