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

无需正则实现元音辅音分组的recompose函数开发求助

实现方案

思路说明

  • 首先定义元音集合,用来快速判断字符是元音还是辅音,全程不使用正则
  • 遍历字符串的每一个字符,对比当前字符和上一个字符的类型(元音/辅音)
    • 类型相同就把当前字符拼入当前分组
    • 类型不同就把当前分组存入结果数组,重新开启新的分组
  • 遍历结束后把最后一个分组存入结果数组,返回最终结果

完整代码

function recompose(str) {
  // 定义元音集合,包含大小写
  const vowels = new Set(['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']);
  const result = [];
  if (!str.length) return result;
  
  let currentGroup = str[0];
  let preType = vowels.has(str[0]) ? 'vowel' : 'consonant';

  for (let i = 1; i < str.length; i++) {
    const currentChar = str[i];
    const currentType = vowels.has(currentChar) ? 'vowel' : 'consonant';
    if (currentType === preType) {
      currentGroup += currentChar;
    } else {
      result.push(currentGroup);
      currentGroup = currentChar;
      preType = currentType;
    }
  }
  // 加入最后一组
  result.push(currentGroup);
  return result;
}

// 测试
console.log(recompose("KiKdaola")); // 输出 [ 'K', 'i', 'Kd', 'ao', 'l', 'a' ]

内容的提问来源于stack exchange,提问作者emre-ozgun

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.14 17:36:06