0

I want my code to convert a snake case string to camel case, also return any underscore at the beginning or ending of the string. Any Help?

function snakeToCamel(str) {
  return str.replace(/[^a-zA-Z0-9]+(.)/g, (m, chr) => {
    return chr.toUpperCase();
  });
}

console.log(snakeToCamel('_user_name')); //Output should be: _userName
console.log(snakeToCamel('the_variable_')); //Output should be: theVariable_
Roko C. Buljan
  • 196,159
  • 39
  • 305
  • 313
  • Does this answer your question? [How to convert snake case to camelcase in my app](https://stackoverflow.com/questions/40710628/how-to-convert-snake-case-to-camelcase-in-my-app) – leonheess Apr 04 '23 at 09:10

2 Answers2

0

Use negative lookahead at the very beginning to ensure you're not at the start of the string, and then match _. Your current pattern matches many things, and not just underscores - if all you want to do is convert snake case to camel case, you want to match just underscores at that point.

function snakeToCamel(str){
  return str.replace(
    /(?!^)_(.)/g,
    (_, char) => char.toUpperCase()
  );
}

console.log(snakeToCamel('_user_name')); //Output should be: _userName
console.log(snakeToCamel('the_variable_')); //Output should be: theVariable_
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
0

If you want a simple tiny library to solve this, and others, problems with case conversions, I recommend you to use CaseParser. It's a powerful lib to do case conversions and after version 2.x.x, it starts to be typed safe for json conversions. I already answered similar question here.

I hope to help you :)

NandoMB
  • 151
  • 1
  • 9