Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
Hongbusi opened this issue Jun 29, 2022 · 4 comments
Open

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

Hongbusi opened this issue Jun 29, 2022 · 4 comments
Labels

Comments

@Hongbusi
Copy link
Member

Hongbusi commented Jun 29, 2022

function underlineToHump(str) {
  return str.replace(/\_(\w)/g, (_, letter) => {
    return letter.toUpperCase()
  })
}
@Hongbusi Hongbusi added handwritten-code today 每日一题。 JS javascript labels Jun 29, 2022
@TickHeart
Copy link
Member

function toHump(str: string): string {
  return str.replace(/\_(\w)/g, (_, letter) => {
    return letter.toUpperCase();
  })
}

@myltx
Copy link

myltx commented Jun 29, 2022

function toHump(str) {
  return str
    .replace(/[_]/g, '/')
    .split('/')
    .reduce((previous, current) => previous + current.replace(/^\w/, (s) => s.toUpperCase()), '');
}

@ChenHaoJie9527
Copy link

组合函数实现

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

@lyx-jay
Copy link

lyx-jay commented Jun 29, 2022

中规中矩的实现

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

@Hongbusi Hongbusi removed the today 每日一题。 label Jun 30, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Development

No branches or pull requests

5 participants