Skip to content

Instantly share code, notes, and snippets.

@jpetitcolas
Created January 8, 2013 06:45
Show Gist options
  • Save jpetitcolas/4481795 to your computer and use it in GitHub Desktop.
Save jpetitcolas/4481795 to your computer and use it in GitHub Desktop.
How to uncamelize a string in Javascript? Example: "HelloWorld" --> "hello_world"
/**
* Uncamelize a string, joining the words by separator character.
* @param string Text to uncamelize
* @param string Word separator
* @return string Uncamelized text
*/
function uncamelize(text, separator) {
// Assume separator is _ if no one has been provided.
if(typeof(separator) == "undefined") {
separator = "_";
}
// Replace all capital letters by separator followed by lowercase one
var text = text.replace(/[A-Z]/g, function (letter) {
return separator + letter.toLowerCase();
});
// Remove first separator (to avoid _hello_world name)
return text.replace("/^" + separator + "/", '');
}
@tyurderi
Copy link

tyurderi commented Sep 3, 2015

Awesome, thank you.

@abdennour
Copy link

More elegance if you want :

function uncamelize(text, separator = "_")  {
 
 return text.replace(/[A-Z]/g,  (letter) => separator + letter.toLowerCase())
              .replace("/^" + separator + "/", '');
 
}

@schrodervictor
Copy link

schrodervictor commented Dec 27, 2018

This is nice, but doesn't fully work. Some problems:

  • Building a RegExp on the fly with simple strings doesn't work. One need to use the RegExp class for that. I was able to get exactly the format it is trying to avoid: uncamelize('FooBar'); yields _foo_bar in the current version.
  • It doesn't handle numbers and leave them concatenated with the previous word.
  • It doesn't handle abbreviations (but this is a hard one :) ). uncamelize('HTTPS'); will result into h_t_t_p_s (actually, _h_t_t_p_s in the current version). The expected behavior would be to get https, but as I said, this is a hard one, because there are legit usages of consecutive capital letters in the camel case, like getANumber.

I'm opening a "pull request" with some suggestions on how to fix the first two problems.

It seems to not be possible to offer you a pull request in the Gist interface... In any case, my suggestions can be found here: https://gist.github.com/schrodervictor/bbbd360a496fee4ac267f9abd20855d1

BTW, the original version is much more "elegant" and easy to understand (it doesn't even need all those comments) than the one suggested by @abdennour. There's absolutely no need to transform it into an one-liner. This is the job of the Minifiers. Keep the source code readable by humans, please.

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