Skip to content

Instantly share code, notes, and snippets.

@jpetitcolas
Created January 8, 2013 06:40
Show Gist options
  • Save jpetitcolas/4481778 to your computer and use it in GitHub Desktop.
Save jpetitcolas/4481778 to your computer and use it in GitHub Desktop.
Camelize a string in Javascript. Example: camelize("hello_world") --> "HelloWorld"
/**
* Camelize a string, cutting the string by separator character.
* @param string Text to camelize
* @param string Word separator (underscore by default)
* @return string Camelized text
*/
function camelize(text, separator) {
// Assume separator is _ if no one has been provided.
if(typeof(separator) == "undefined") {
separator = "_";
}
// Cut the string into words
var words = text.split(separator);
// Concatenate all capitalized words to get camelized string
var result = "";
for (var i = 0 ; i < words.length ; i++) {
var word = words[i];
var capitalizedWord = word.charAt(0).toUpperCase() + word.slice(1);
result += capitalizedWord;
}
return result;
}
@gunn
Copy link

gunn commented Nov 14, 2018

const camelize = (text, separator="_")=> (
  text.split(separator)
      .map(w=> w.replace(/./, m=> m.toUpperCase()))
      .join()
)

@cpmech
Copy link

cpmech commented Jun 12, 2019

Nice, Thanks!

I think you'll need an empty quotes "" in the join command:

const camelize = (text, separator="_")=> (
  text.split(separator)
      .map(w=> w.replace(/./, m=> m.toUpperCase()))
      .join("")
)

@DaveBitter
Copy link

DaveBitter commented Mar 25, 2020

My two cents :) :

const camelize = (text, separator = '_') => text
   .split(separator)
   .reduce((acc, cur) => `${acc}${cur.charAt(0).toUpperCase() + cur.slice(1)}`, '');

Thanks for the base though!

@kasir-barati
Copy link

@jpetitcolas, @r72cccp, @gunn, @DaveBitter your code is pascalize not camalize

this code is camalize. why you guys read it machine-readable, not human-readable?

/**
 *
 * @param {string} text
 * @param {string} separator
 * @return {string}
 */
function camelize(text, separator = '-') {
  let words = text.split(separator);
  let result = '';

  words.forEach((word, index) => {
    if (index === 0) {
      word = word.replace(/./, (letter) => letter.toLowerCase());
      result += word;
      return;
    }
    word = word.replace(/./, (letter) => letter.toUpperCase());
    result += word;
  });
  return result;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment