0

我没有用正则表达式做很多工作,我被卡住了。我正在尝试获取一个字符串并将其设为标题大小写,但有一些例外。我还想删除任何空格。

目前它正在删除空格并且标题案例正在工作,但它没有遵循例外情况。有没有办法将“title”变量与“regex”变量结合起来,并使其异常有效?

const toTitleCase = str => {
  const title = str.replace(/\s\s+/g, ' ');
  const regex = /(^|\b(?!(AC | HVAC)\b))\w+/g;
  const updatedTitle = title
    .toLowerCase()
    .replace(regex, (s) => s[0].toUpperCase() + s.slice(1));

  return updatedTitle;
}

console.log(toTitleCase(`this is an HVAC AC converter`))

4

1 回答 1

1

从上面的评论...

“看起来 OP 想要排除单词'AC''HVAC'从标题替换中排除。可以实现这一点的模式是例如\b(?!HVAC|AC)(?<upper>[\w])(?<lower>[\w]+)\b

涵盖所有 OP 要求的代码可能类似于以下示例...

function toTitleCase(value) {
  return String(value)
    .trim()
    .replace(/\s+/g, ' ')
    .replace(
      /\b(?!HVAC|AC)(?<upper>[\w])(?<lower>[\w]+)\b/g,
      (match, upper, lower) => `${ upper.toUpperCase() }${ lower.toLowerCase() }`,
    );
}

console.log(
  "toTitleCase('  This  is an HVAC   AC converter. ') ...",
  `'${ toTitleCase('  This  is an HVAC   AC converter. ') }'`
);
.as-console-wrapper { min-height: 100%!important; top: 0; }

通过提供要排除的单词作为附加参数,可以进一步采取上述方法......

function toTitleCase(value, ...exludedWordList) {
  const exceptions = exludedWordList
    .flat(Infinity)
    .map(item => String(item).trim())
    .join('|');
  return String(value)
    .trim()
    .replace(/\s+/g, ' ')
    .replace(
      RegExp(`\\b(?!${ exceptions })(?<upper>[\\w])(?<lower>[\\w]+)\\b`, 'g'),
      (match, upper, lower) => `${ upper.toUpperCase() }${ lower.toLowerCase() }`,
    );
}

console.log(
  "toTitleCase('  this  is an HVAC   AC converter. ', ['AC', 'HVAC']) ...",
  `'${ toTitleCase('  this  is an HVAC   AC converter. ', ['AC', 'HVAC']) }'`
);
console.log(
  "toTitleCase('  this  is an HVAC   AC converter. ', 'is', 'an', 'converter') ...",
  `'${ toTitleCase('  this  is an HVAC   AC converter. ', 'is', 'an', 'converter') }'`
);
.as-console-wrapper { min-height: 100%!important; top: 0; }

于 2022-01-31T18:49:20.783 回答