Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert hyphens to camel case (camelCase)

People also ask

What is CamelCase conversion?

Camel case (sometimes stylized as camelCase or CamelCase, also known as camel caps or more formally as medial capitals) is the practice of writing phrases without spaces or punctuation. It indicates the separation of words with a single capitalized letter, and the first word starting with either case.


Try this:

var camelCased = myString.replace(/-([a-z])/g, function (g) { return g[1].toUpperCase(); });

The regular expression will match the -i in marker-image and capture only the i. This is then uppercased in the callback function and replaced.


This is one of the great utilities that Lodash offers if you are enlightened and have it included in your project.

var str = 'my-hyphen-string';
str = _.camelCase(str);
// results in 'myHyphenString'

You can get the hypen and the next character and replace it with the uppercased version of the character:

var str="marker-image-test";
str.replace(/-([a-z])/g, function (m, w) {
    return w.toUpperCase();
});

Here's my version of camelCase function:

var camelCase = (function () {
    var DEFAULT_REGEX = /[-_]+(.)?/g;

    function toUpper(match, group1) {
        return group1 ? group1.toUpperCase() : '';
    }
    return function (str, delimiters) {
        return str.replace(delimiters ? new RegExp('[' + delimiters + ']+(.)?', 'g') : DEFAULT_REGEX, toUpper);
    };
})();

It handles all of the following edge cases:

  • takes care of both underscores and hyphens by default (configurable with second parameter)
  • string with unicode characters
  • string that ends with hyphens or underscore
  • string that has consecutive hyphens or underscores

Here's a link to live tests: http://jsfiddle.net/avKzf/2/

Here are results from tests:

  • input: "ab-cd-ef", result: "abCdEf"
  • input: "ab-cd-ef-", result: "abCdEf"
  • input: "ab-cd-ef--", result: "abCdEf"
  • input: "ab-cd--ef--", result: "abCdEf"
  • input: "--ab-cd--ef--", result: "AbCdEf"
  • input: "--ab-cd-__-ef--", result: "AbCdEf"

Notice that strings that start with delimiters will result in a uppercase letter at the beginning. If that is not what you would expect, you can always use lcfirst. Here's my lcfirst if you need it:

function lcfirst(str) {
    return str && str.charAt(0).toLowerCase() + str.substring(1);
}

This doesn't scream out for a RegExp to me. Personally I try to avoid regular expressions when simple string and array methods will suffice:

let upFirst = word => 
  word[0].toUpperCase() + word.toLowerCase().slice(1)

let camelize = text => {
  let words = text.split(/[-_]/g) // ok one simple regexp.
  return words[0].toLowerCase() + words.slice(1).map(upFirst)
}

camelize('marker-image') // markerImage