CamelCase to snake_case and vice versa with JavaScript

Snake case to camel case:


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

… and camel case to snake case:

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

Leave a Reply

Your email address will not be published. Required fields are marked *