regex 将蛇形大小写字符串转换为标题大小写

irtuqstp  于 2023-11-20  发布在  其他
关注(0)|答案(4)|浏览(115)

我有下面的snake case变量big_animal
我想转换成Big Animal
方法是str => str.replace(/([-_]\w)/g, g => g[1].toUpperCase());
但我一直得到bigAnimal,但我想保留空格,首字母大写。

9avjhtql

9avjhtql1#

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

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'))

字符串
这个版本处理多个连续的下划线。它对第一个字符(或带前导下划线的字符)和多个下划线后面的字符进行单独的匹配,并在后者中添加一个空格。

更新

经过反思,我认为用两个regex replaces来做这件事会更好:

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'))


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

ckocjqey

ckocjqey2#

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

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);

字符串

jslywgbw

jslywgbw3#

如果你想坚持使用正则表达式方法。

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);

字符串

dxxyhpgq

dxxyhpgq4#

下面是基于上述解决方案的类型脚本等效物

/**
 * String Converter to convert snake_case to Title Case
 * Eg.
 * - quick_brown_fox -> Quick Brown Fox
 * - quick_brown____fox -> Quick Brown Fox
 * - quick_brown_fox----jumps_over -> Quick Brown Fox Jumps Over
 *
 */

const convertSnakeToTitleCase = (s: string): string =>
  s
    .replace(/^[-_]*(.)/, (_, c: string) => c.toUpperCase())
    .replace(/[-_]+(.)/g, (_, c: string) => ' ' + c.toUpperCase());

字符串
这是基于JEST的测试

import { convertSnakeToTitleCase } from './helpers';

describe('convertSnakeToTitleCase helper function unit tests', () => {
  it('returns correct output for regular snake case string', () => {
    expect(convertSnakeToTitleCase('quick_brown_fox')).toBe('Quick Brown Fox');
  });

  it('returns correct output for snake case strings with consecutive underscores', () => {
    expect(convertSnakeToTitleCase('quick_brown_____fox')).toBe(
      'Quick Brown Fox'
    );
  });

  it('returns correct output for snake case strings with hyphen separated strings', () => {
    expect(convertSnakeToTitleCase('quick_brown_fox-----jumps_over')).toBe(
      'Quick Brown Fox Jumps Over'
    );
  });
});

相关问题