Created
August 24, 2012 13:06
-
-
Save tan-yuki/3450323 to your computer and use it in GitHub Desktop.
camel case to snake case
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
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; | |
}; |
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
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