Conversion of camel case string into snake case and vice-versa

September 15, 2019 Off By admin_manish

I know, I know this is basic but basic is very important and I believe we should always explore new ways to implement basics.

Today I am going to talk about one way for this conversion. As always there are multiple ways to solve this but I am sharing what I implemented in one of my interviews and got the result.

Snake case to camel case

function snakeCaseToCamelCase(value) {
    return value.replace(/([_-]\w)/g, function(m){
           return m[1].toUpperCase();
       });
}

Camel case to snake case

function camelCaseToSnakeCase(value) {
    return value.replace(/[\w]([A-Z])/g, function(m) {
        return m[0] + '_' + m[1];
    }).replace(/[A-Z]([A-Z])/g, function(m) {
        return m[0] + '_' + m[1];
    }).toLowerCase();

}

Main method

function convertInput(input1) {
 if (input1.indexOf('_') >= 0) {
     return snakeCaseToCamelCase(input1);
 } else {
     return camelCaseToSnakeCase(input1);
 }
}

Now you can verify the output using the following:

console.log(convertInput('this_is_a_variable-name')); // output: thisIsAVariableName
console.log(convertInput('javaIsAGreatLanguage')); //output: java_is_a_great_language

Hope this will help you or if you have a string which contains other characters then you can change your regular expression or add more replace method call.

Enjoy coding!!