如何 title-case 带有一些排除的单词异常的字符串以及如何 collapse/trim 额外的白色 space 序列?

How to title-case a string with some excluded word exceptions and how to collapse/trim additional white space sequences as well?

我没有用正则表达式做很多工作,而且我被卡住了。我正在尝试使用一个字符串并将其设为首字母大写,但有一些例外。我也想删除任何空格。

目前它正在删除空格并且标题大小写工作正常,但它没有遵循例外情况。有没有办法将“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`))

从上面的评论...

"It looks like the OP wants to exclude the words 'AC' and 'HVAC' from the title-case replacement. A pattern which would achieve this is e.g. \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; }