[SOLVED] convert snake case to camel case in javascript

Issue

This Content is from Stack Overflow. Question asked by Elom Passah

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_



Solution

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_


This Question was asked in StackOverflow by Elom Passah and Answered by CertainPerformance It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?