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

如何在JS中基于自定义字符分值处理匹配的带连字符单词?

解决方案

核心思路是先实现一个自定义字符分值计算函数,把原来基于字符数的判断逻辑替换为基于总分值的判断。

1. 编写字符分值计算函数

这个函数遍历字符串的每个字符,按照a-m得2分,n-z得1分的规则累加总分:

function getCharScore(str) {
  let totalScore = 0;
  // 统一转小写避免大小写影响判断
  const lowerStr = str.toLowerCase();
  for (const char of lowerStr) {
    if (char >= 'a' && char <= 'm') {
      totalScore += 2;
    } else if (char >= 'n' && char <= 'z') {
      totalScore += 1;
    }
    // 非字母字符(如连字符)不计入分值
  }
  return totalScore;
}

2. 修改原替换逻辑

把原来基于字符长度的判断,替换为基于总分值的判断(允许的最高总分设为10):

.replace(/\b((\w+?)\-)((\w+?)(\-(\w+?))?)\b/g, (_, a, b, c, d, e, f) => {
  // 计算所有字母部分的总分值(b、d、f是拆分出的单词段)
  let totalScore = getCharScore(b);
  if (d) totalScore += getCharScore(d);
  if (f) totalScore += getCharScore(f);

  const maxAllowedScore = 10;
  // 根据总分值判断是否替换为非断字连字符
  if (f && totalScore <= maxAllowedScore) {
    return `${b}\‑${d}\‑${f}`;
  } else if (!f && totalScore <= maxAllowedScore) {
    return `${b}\‑${d}`;
  } else {
    return _;
  }
})

逻辑说明

  • 拆分出匹配到的各个单词段(b、d、f),分别计算它们的分值并累加得到总分
  • 如果总分≤10,就把普通连字符替换为非断字连字符(‑);否则保持原字符串不变
  • 兼容了单连字符(如test-case)和双连字符(如test-case-example)的情况

示例验证

  • 对于mmmm-mmm:每个m属于a-m区间,得2分,7个字符总分14>10,不替换
  • 对于tttt-ttt:每个t属于n-z区间,得1分,7个字符总分7≤10,替换为tttt‑ttt

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 07:43:15