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

JS字符串处理:提取前两个大写开头单词并转小写连字符形式

解决方案

可以通过正则匹配提取大写开头单词结合字符串处理方法实现需求,下面以JavaScript为例给出具体实现:

实现代码

function formatTargetString(input) {
  // 截断连字符及之后的内容
  const prefix = input.split('-')[0];
  // 匹配所有以大写字母开头的单词(大写+后续小写字母)
  const capitalizedWords = prefix.match(/[A-Z][a-z]+/g) || [];
  // 取前2个单词,转小写后用连字符连接
  return capitalizedWords.slice(0, 2).map(word => word.toLowerCase()).join('-');
}

// 测试用例
console.log(formatTargetString('SourceSansPro-ExtraLight')); // 输出: source-sans
console.log(formatTargetString('RobotoSlab-Italic')); // 输出: roboto-slab
console.log(formatTargetString('Lora-Regular')); // 输出: lora
console.log(formatTargetString('OpenSansCondensed-SemiBold')); // 输出: open-sans

步骤说明

  1. 截断连字符内容:用split('-')[0]获取输入字符串中连字符之前的部分,比如SourceSansPro-ExtraLight会得到SourceSansPro。
  2. 提取大写开头单词:使用正则/[A-Z][a-z]+/g匹配所有以大写字母开头、后续跟小写字母的单词序列,能精准提取每个驼峰式的单词。
  3. 处理结果格式:用slice(0,2)取前两个匹配到的单词,转小写后通过join('-')用连字符连接,得到最终结果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 09:36:23