Skip to content

Instantly share code, notes, and snippets.

@hallojoe
Last active June 5, 2018 10:21
Show Gist options
  • Save hallojoe/fb1706d474317eb3ca42bbd1da619830 to your computer and use it in GitHub Desktop.
Save hallojoe/fb1706d474317eb3ca42bbd1da619830 to your computer and use it in GitHub Desktop.
Javascript kebab case helpers
/*
https://run.plnkr.co/plunks/Sv54t4/
*/
function anyToKebab(s) {
if('string' !== typeof s) return s;
var result = '', i = 0, len = s.length;
for(; i < len; i++)
if(s[i] === s[i].toUpperCase())
result += '-' + s[i].toLowerCase();
else
result += s[i].toLowerCase();
return result[0] !== '-' ? result : result.substr(1);
}
function kebabToPascal(s) {
if('string' !== typeof s || s.length === 0) return s;
var result = s.substr(0,1).toUpperCase(), i = 1, len = s.length;
for(; i < len; i++)
if(s[i] === '-' && i+1 !== len) {
result += s[i+1].toUpperCase();
i++;
}
else
result += s[i].toLowerCase();
return result[0] !== '-' ? result : result.substr(1);
}
function kebabToCamel(s) {
if('string' !== typeof s) return s;
var p = kebabToPascal(s);
return p.substr(0,1).toLowerCase() + p.substring(1);
}
console.log('testing empty string to kebab')
var input = '', output = anyToKebab(input);
if(input === output)
console.log('nothing happend...');
else
console.log(input, ' -> ', output);
console.log('testing invalid type to kebab')
input = 1000, output = anyToKebab(1000);
if(input === output)
console.log('nothing happend...');
else
console.log(input, ' -> ', output);
console.log('testing camel to kebab')
input = 'someCamelCaseString', output = anyToKebab(input);
if(input === output)
console.log('nothing happend...');
else
console.log(input, ' -> ', output);
console.log('testing pascal to kebab')
input = 'SomePascalCaseString', output = anyToKebab(input);
if(input === output)
console.log('nothing happend...');
else
console.log(input, ' -> ', output);
console.log('testing kebab to pascal')
input = 'some-kebab-case-string', output = kebabToPascal(input);
if(input === output)
console.log('nothing happend...');
else
console.log(input, ' -> ', output);
console.log('testing kebab to camel')
output = kebabToCamel(input);
if(input === output)
console.log('nothing happend...');
else
console.log(input, ' -> ', output);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment