JavaScript: transform slug to camel case

I refactor my atom packages at the moment and one thing I changed was loading classes from other files. Before, everything was hard-coded and it should be more generic, especially facing future changes. Because I used kind of slug strings internally, I created a function which converts slugs into camel case. Perhaps you need such code?

Using it without parameters, output is lower camel case. You can set type to upper when you want to have upper camel case. Additionally you can set the separator characters. Default characters are ‘-_.’ (dash, underscore and dot).

Code:

String.prototype.capitalize = function() {
    return this.charAt(0).toUpperCase() + this.slice(1);
}

String.prototype.uncapitalize = function() {
    return this.charAt(0).toLowerCase() + this.slice(1);
}

String.prototype.slugToCamelCase = function(type, separators) {
    if (!separators || typeof separators != 'string') {
        separators = '-_.';
    }
    var result = this.replace(new RegExp('[' + separators + '][a-z]', 'ig'), function (s) {
	    return s.substr(1, 1).toUpperCase();
	});
    if (type == 'upper') {
        result = result.capitalize();
    }
    else {
        result = result.uncapitalize();
    }
    return result;
}

Examples:

var str = 'this-is-just-a-test'.slugToCamelCase() );
// str: thisIsJustATest

var str = 'this-is_just.a-test'.slugToCamelCase() );
// str: thisIsJustATest

var str = 'this-is-just-a-test'.slugToCamelCase('upper) );
// str: ThisIsJustATest

var str = 'this/is/just/a/test'.slugToCamelCase(null, '|') );
// str: thisIsJustATest

Leave a Reply

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

Captcha * Time limit is exhausted. Please reload CAPTCHA.