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

求正则表达式实现字符串分割并转为连字符分隔小写格式

解决方案

你可以使用以下正则表达式实现需求:

/(?=[A-Z])|[\s_.-]/

完整代码示例

const originalStr = "AQuickBrown_fox jump over the-lazy-Dog";
const formattedStr = originalStr
  .split(/(?=[A-Z])|[\s_.-]/)
  .filter(Boolean) // 过滤分割后可能出现的空字符串
  .join("-")
  .toLowerCase();

console.log(formattedStr); // 输出: "a-quick-brown-fox-jump-over-the-lazy-dog"

正则表达式解释

  • (?=[A-Z]):正向零宽断言,匹配任何紧跟大写字母的位置,用来分割驼峰结构的大写字母前缀(比如把"AQuick"拆成["A", "Quick"])
  • |[\s_.-]:字符集匹配,直接匹配空格、下划线、点号、连字符这些需要替换为连字符的分隔符
  • filter(Boolean):处理分割后可能出现的空字符串(比如连续分隔符场景),让结果更健壮

替代方案(使用replace更高效)

如果不想用split+join,也可以直接通过两次替换完成:

const originalStr = "AQuickBrown_fox jump over the-lazy-Dog";
const formattedStr = originalStr
  .replace(/(?=[A-Z])|[\s_.-]/g, "-")
  .toLowerCase()
  .replace(/-+/g, "-") // 合并连续的连字符
  .replace(/^-|-$/g, ""); // 去除首尾可能的连字符

console.log(formattedStr);

内容的提问来源于stack exchange,提问作者Bibek Kshetri

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 01:35:09