Skip to content

Instantly share code, notes, and snippets.

@tdukart
Last active February 2, 2020 05:53
Show Gist options
  • Save tdukart/b87afb278c41245741ae7a0c355a0a0b to your computer and use it in GitHub Desktop.
Save tdukart/b87afb278c41245741ae7a0c355a0a0b to your computer and use it in GitHub Desktop.
JavaScript Kebab Case function
/**
* Given a string, converts it to kebab case (lowercase, hyphen-separated). For example,
* "makeFoo" becomes "make-foo", and "a Multi Word string" becomes "a-multi-word-string".
*
* @param {string} string Your input string.
* @returns {string} Kebab-cased string.
*/
function kebabCase(string) {
var result = string;
// Convert camelCase capitals to kebab-case.
result = result.replace(/([a-z][A-Z])/g, function (match) {
return match.substr(0, 1) + '-' + match.substr(1, 1).toLowerCase();
});
// Convert non-camelCase capitals to lowercase.
result = result.toLowerCase();
// Convert non-alphanumeric characters to hyphens
result = result.replace(/[^-a-z0-9]+/g, '-');
// Remove hyphens from both ends
result = result.replace(/^-+/, '').replace(/-+$/, '');
return result;
}
@fmcat
Copy link

fmcat commented Jul 25, 2019

Can you please explain how it works?

Todd does a good job explaining it in the function comment declaration:

 * Given a string, converts it to kebab case (lowercase, hyphen-separated). For example,
 * "makeFoo" becomes "make-foo", and "a Multi Word string" becomes "a-multi-word-string".

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment