You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求VS Code用户代码片段:将文件名从驼峰式转短横线式

驼峰式命名转短横线式命名的实现方案

下面提供几种主流编程语言的实现方式,能高效完成MyCustomeComponents到my-custom-components的转换:

JavaScript实现

function camelToKebab(str) {
  // 匹配小写字母/数字与大写字母的分界,插入短横线后转全小写
  return str.replace(/([a-z0-9]|(?=[A-Z]))([A-Z])/g, '$1-$2').toLowerCase();
}

// 测试示例
console.log(camelToKebab('MyCustomeComponents')); // 输出: my-custom-components

Python实现

import re

def camel_to_kebab(s):
    # 通过正则匹配大小写分界,插入短横线后转小写
    return re.sub(r'([a-z0-9])([A-Z])', r'\1-\2', s).lower()

# 测试示例
print(camel_to_kebab('MyCustomeComponents')) # 输出: my-custom-components

实现逻辑说明

核心思路是利用正则表达式匹配小写字母/数字与大写字母的分界位置,在两者之间插入短横线,最后将整个字符串转换为小写。这种方式能兼容大多数驼峰命名场景,包括包含连续大写字母的情况(比如HTMLInput会转为html-input)。

内容的提问来源于stack exchange,提问作者Harry.Hao

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 15:02:02