Skip to content

Instantly share code, notes, and snippets.

@tan-yuki
Created August 24, 2012 13:06
Show Gist options
  • Save tan-yuki/3450323 to your computer and use it in GitHub Desktop.
Save tan-yuki/3450323 to your computer and use it in GitHub Desktop.
camel case to snake case
String.prototype.toSnakeCase = function() {
var upperChars = this.match(/([A-Z])/g);
if (! upperChars) {
return this;
}
var str = this.toString();
for (var i = 0, n = upperChars.length; i < n; i++) {
str = str.replace(new RegExp(upperChars[i]), '_' + upperChars[i].toLowerCase());
}
if (str.slice(0, 1) === '_') {
str = str.slice(1);
}
return str;
};
test('camelToSnake', function() {
var testCtoS = function(str, expect) {
equal(str.toSnakeCase(), expect);
};
testCtoS('aaaa', 'aaaa');
testCtoS('Aaaa', 'aaaa');
testCtoS('AAaa', 'a_aaa');
testCtoS('aAaA', 'a_aa_a');
testCtoS('toLocaleDateString', 'to_locale_date_string');
testCtoS('ABCDE', 'a_b_c_d_e');
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment