Convert hyphens to camel case (camelCase)

Viewed 82808

With regex (i assume) or some other method, how can i convert things like:

marker-image or my-example-setting to markerImage or myExampleSetting.

I was thinking about just splitting by - then convert the index of that hypen +1 to uppercase. But it seems pretty dirty and was hoping for some help with regex that could make the code cleaner.

No jQuery...

16 Answers

Use String's replace() method with a regular expression literal and a replacement function.

For example:

'uno-due-tre'.replace(/-./g, (m) => m[1].toUpperCase()) // --> 'unoDueTre'

Explanation:

  • 'uno-due-tre' is the (input) string that you want to convert to camel case.
  • /-./g (the first argument passed to replace()) is a regular expression literal.
    • The '-.' (between the slashes) is a pattern. It matches a single '-' character followed by any single character. So for the string 'uno-due-tre', the pattern '-.' matches '-d' and '-t' .
    • The 'g' (after the closing slash) is a flag. It stands for "global" and tells replace() to perform a global search and replace, ie, to replace all matches, not just the first one.
  • (m) => m[1].toUpperCase() (the second argument passed to replace()) is the replacement function. It's called once for each match. Each matched substring is replaced by the string this function returns. m (the first argument of this function) represents the matched substring. This function returns the second character of m uppercased. So when m is '-d', this function returns 'D'.
  • 'unoDueTre' is the new (output) string returned by replace(). The input string is left unchanged.

Here is my implementation (just to make hands dirty)

/**
 * kebab-case to UpperCamelCase
 * @param {String} string
 * @return {String}
 */
function toUpperCamelCase(string) {
  return string
    .toLowerCase()
    .split('-')
    .map(it => it.charAt(0).toUpperCase() + it.substring(1))
    .join('');
}

You can use camelcase from NPM.

npm install --save camelcase

const camelCase = require('camelcase');
camelCase('marker-image'); // => 'markerImage';
camelCase('my-example-setting'); // => 'myExampleSetting';

Just a version with flag, for loop and without Regex:

function camelCase(dash) { 

  var camel = false;
  var str = dash;
  var camelString = '';

  for(var i = 0; i < str.length; i++){
    if(str.charAt(i) === '-'){
      camel = true;

    } else if(camel) {
      camelString += str.charAt(i).toUpperCase();
      camel = false;
    } else {
      camelString += str.charAt(i);
    }
  } 
  return camelString;
}

Use this if you allow numbers in your string.

Obviously the parts that begin with a number will not be capitalized, but this might be useful in some situations.

function fromHyphenToCamelCase(str) {
  return str.replace(/-([a-z0-9])/g, (g) => g[1].toUpperCase())
}

function fromHyphenToCamelCase(str) {
  return str.replace(/-([a-z0-9])/g, (g) => g[1].toUpperCase())
}

const str1 = "category-123";
const str2 = "111-222";
const str3 = "a1a-b2b";
const str4 = "aaa-2bb";

console.log(`${str1} => ${fromHyphenToCamelCase(str1)}`);
console.log(`${str2} => ${fromHyphenToCamelCase(str2)}`);
console.log(`${str3} => ${fromHyphenToCamelCase(str3)}`);
console.log(`${str4} => ${fromHyphenToCamelCase(str4)}`);

You can also use string and array methods; I used trim to avoid any spaces.

const properCamel = (str) =>{

  const lowerTrim = str.trim().toLowerCase(); 

  const array = lowerTrim.split('-');

  const firstWord = array.shift();

  const caps = array.map(word=>{

    return word[0].toUpperCase() + word.slice(1);

  })

  caps.unshift(firstWord)

  return caps.join('');

}

This simple solution takes into account these edge cases.

  • Single word
  • Single letter
  • No hyphen
  • More than 1 hyphen

const toCamelCase = (text) => text.replace(/(.)([^-|$]*)[-]*/g, (_,letter,word) => `${letter.toUpperCase()}${word.toLowerCase()}`)

Related