Skip to content

Instantly share code, notes, and snippets.

@schrodervictor
Forked from jpetitcolas/uncamelize.js
Last active August 6, 2019 14:52
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save schrodervictor/bbbd360a496fee4ac267f9abd20855d1 to your computer and use it in GitHub Desktop.
Save schrodervictor/bbbd360a496fee4ac267f9abd20855d1 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 - Text to uncamelize
* @param {string} [separator='_'] - Word separator
* @returns {string} Uncamelized text
*/
function uncamelize(text, separator) {
// Assume separator is _ if no one has been provided.
if('undefined' === typeof separator) {
separator = '_';
}
// Replace all capital letters and group of numbers by the
// separator followed by lowercase version of the match
var text = text.replace(/[A-Z]|\d+/g, function(match) {
return separator + match.toLowerCase();
});
// Remove first separator (to avoid _hello_world name)
return text.replace(new RegExp('^' + separator), '');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment