Skip to content

Instantly share code, notes, and snippets.

@juniorgarcia
Created December 7, 2015 02:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save juniorgarcia/a826eb213fe1958a4c81 to your computer and use it in GitHub Desktop.
Save juniorgarcia/a826eb213fe1958a4c81 to your computer and use it in GitHub Desktop.
Simple cases conversion using JavaScript
/* Using functional programming to convert cases */
function convertCase(text, callback) {
return callback.apply(null, [text]);
}
/* convert_to_snake_case */
function snakeCase(text) {
return text.replace(/\s+/g, '_').toLowerCase();
}
/* ConvertToCamelCase */
function camelCase(text) {
return text
.replace(/\s([a-z])/g, function($1) { return $1.toUpperCase() })
.replace(/\s/g, '')
.replace(/^([A-Z])/, function($1) { return $1.toLowerCase() });
}
/* CONVERT_TO_CONSTANT_CASE */
function constantCase(text) {
var result = convertCase(text, snakeCase);
return result.toUpperCase();
}
/* ConvertPascalCase */
function pascalCase(text) {
return convertCase(text, camelCase)
.replace(/^([a-z])/, function($1) { return $1.toUpperCase(); });
}
/* CoNvErTtOtOgGlEcAsE */
function toggleCase(text) {
var lowerCase = text[0].match(/[a-z]/) == null;
var arrText = text.split('');
arrText.forEach(function(item, index) {
arrText[index] = lowerCase ? item.toUpperCase() : item.toLowerCase();
lowerCase = !lowerCase;
});
return arrText.join('');
}
var strTest = "insert a test here";
console.log("snake_case:\n\t" + convertCase(strTest, snakeCase));
console.log("camelCase:\n\t" + convertCase(strTest, camelCase));
console.log("CONSTANT_CASE:\n\t" + convertCase(strTest, constantCase));
console.log("PascalCase:\n\t" + convertCase(strTest, pascalCase));
console.log("tOgGlEcAsE:\n\t" + convertCase(strTest, toggleCase));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment