将字符串转换为JavaScript中的标题大小写

时间:2020-10-22 19:39:32

标签: javascript string replace

我觉得我缺少什么。

我有以下蛇形变量big_animal 我想将其转换为Big Animal

所以我运行了此方法str.replace(/([-_]\w)/g, g => g[1].toUpperCase());

但是我一直得到bigAnimal,但是我想保留空格并首字母大写

3 个答案:

答案 0 :(得分:3)

首先用下划线分隔字符串。然后大写第一个字母。

let str = "big_animal";

let ret = str
  .split("_")
  .filter(x => x.length > 0)
  .map((x) => (x.charAt(0).toUpperCase() + x.slice(1)))
  .join(" ");
console.log(ret);

答案 1 :(得分:1)

如果您要坚持使用正则表达式方法。

let str = "big_animal_and_more"
let output = str.replace(/(^\w)/g, g => g[0].toUpperCase()).replace(/([-_]\w)/g, g => " " + g[1].toUpperCase()).trim();
console.log(output);

答案 2 :(得分:1)

另一个普通的正则表达式版本:

const titleCase = (s) =>
  s.replace(/^_*(.)|_+(.)/g, (s, c, d) => c ? c.toUpperCase() : ' ' + d.toUpperCase())

console .log (titleCase ('big_animal'))
console .log (titleCase ('_big_animal___with_more_Nodes'))

此版本处理多个连续的下划线。它对第一个字符(或带有下划线的字符)有单独的匹配项,而在多个下划线之后的字符具有单独的匹配项,为后者添加一个空格。

更新

反思,我认为最好用两个正则表达式替换:

const titleCase = (s) =>
  s.replace (/^[-_]*(.)/, (_, c) => c.toUpperCase())       // Initial char (after -/_)
   .replace (/[-_]+(.)/g, (_, c) => ' ' + c.toUpperCase()) // First char after each +/_

console .log (titleCase ('big_animal'))
console .log (titleCase ('_big_animal___with-more--Nodes'))

此变体还增加了对烤肉串情况的处理。

相关问题