Learn how to camelize and decamelize strings easily in JavaScript.

When you work with logic to create plugins, libraries and other things e.g frameworks, you will need to create the representation in camel case of string or convert a camelcased string into a custom representation dinamically. If you need to do it in your favorite technology, JavaScript, we'll show you in this article 2 simple snippets that will help you to convert any string into its camel case version and viceversa.

Camelize

The following camelize function receives as first argument the text that you want to camelize. As you know, a string can be either separated by a single space, an underscore, an hyphen, so the camelize function will automatically convert them all:

/**
 * Camelize a string, cutting the string by multiple separators like
 * hyphens, underscores and spaces.
 * 
 * @param {text} string Text to camelize
 * @return string Camelized text
 */
function camelize(text) {
    return text.replace(/^([A-Z])|[\s-_]+(\w)/g, function(match, p1, p2, offset) {
        if (p2) return p2.toUpperCase();
        return p1.toLowerCase();        
    });
}

The following examples show the result of the camelize function:

// someDatabaseFieldName
console.log(camelize("some_database_field_name"));

// someLabelThatNeedsToBeCamelized
console.log(camelize("Some label that needs to be camelized"));

// someJavascriptProperty
console.log(camelize("some-javascript-property"));

// someMixedStringWithSpacesUnderscoresAndHyphens
console.log(camelize("some-mixed_string with spaces_underscores-and-hyphens"));

Decamelize

By the decamelization process, you will need to provide as first argument to the decamelize function the string in camel case that you want to decamelize, as second argument the separator that will be used to separate every camelized word:

/**
 * Decamelizes a string with/without a custom separator (underscore by default).
 * 
 * @param str String in camelcase
 * @param separator Separator for the new decamelized string.
 */
function decamelize(str, separator){
	separator = typeof separator === 'undefined' ? '_' : separator;

	return str
        .replace(/([a-z\d])([A-Z])/g, '$1' + separator + '$2')
        .replace(/([A-Z]+)([A-Z][a-z\d]+)/g, '$1' + separator + '$2')
        .toLowerCase();
}

Examples of decamelize:

// some database field name (separate with an empty space)
console.log(decamelize("someDatabaseFieldName", " "));

// some-label-that-needs-to-be-camelized (separate with an hyphen)
console.log(decamelize("someLabelThatNeedsToBeCamelized", "-"));

// some_javascript_property (separate with underscore)
console.log(decamelize("someJavascriptProperty", "_"));

Happy coding !


Senior Software Engineer at Software Medico. Interested in programming since he was 14 years old, Carlos is a self-taught programmer and founder and author of most of the articles at Our Code World.

Sponsors