-
-
Save schrodervictor/bbbd360a496fee4ac267f9abd20855d1 to your computer and use it in GitHub Desktop.
How to uncamelize a string in Javascript? Example: "HelloWorld" --> "hello_world"
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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