Skip to content

写个函数, 可以转化下划线命名到驼峰命名 #24

Open

Description

@Hongbusi
function underlineToHump(str) {
  return str.replace(/\_(\w)/g, (_, letter) => {
    return letter.toUpperCase()
  })
}

Activity

  1. TickHeart commented on Jun 29, 2022

    @TickHeart
    Member
    function toHump(str: string): string {
      return str.replace(/\_(\w)/g, (_, letter) => {
        return letter.toUpperCase();
      })
    }
  2. myltx commented on Jun 29, 2022

    @myltx
    function toHump(str) {
      return str
        .replace(/[_]/g, '/')
        .split('/')
        .reduce((previous, current) => previous + current.replace(/^\w/, (s) => s.toUpperCase()), '');
    }
  3. ChenHaoJie9527 commented on Jun 29, 2022

    @ChenHaoJie9527

    组合函数实现

    const compose = (...args: any[]) => values => args.reverse().reduce((prev, current)=> current(prev), values);
    const strReplace = (str: string) => str.replace(/[_]/g, '');
    const strToUpperCase = (str: string) => str.replace(/w/g, (strs, letter) => {
      return strs.toUpperCase();
    })
    
    const flowRight = compose(strToUpperCase, strReplace);
    console.log('flowRight: ', flowRight('hello_world'));
  4. lyx-jay commented on Jun 29, 2022

    @lyx-jay

    中规中矩的实现

    function trans(str:string):string {
      if (!str.includes('_')) return str;
      let flag:boolean = false;
      let res:string = "";
      for (let i = 0; i < str.length; i++) {
        if (str[i] !== '_') {
          res += (flag && i !== 1) ? str[i].toUpperCase() : str[i]
          flag = false;
        } else {
          flag = true;
        }
      }
      return res;
    }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions