Skip to content

Instantly share code, notes, and snippets.

@tdukart
Last active February 2, 2020 05:53
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • 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;
}
@lapo-luchini
Copy link

Last regex is missing a +, so multiple trailing - will not be caught.

@dimkir
Copy link

dimkir commented Oct 6, 2017

And maybe add 3rd replace: .replace(/-{2,}/, '-'); so that multiple -- are converted to one. (happens in case you have If you use js- prefix which turns into if-you-use-js--prefix without additional replace

@soulilya
Copy link

Add Unicode support.

@Moeen-Ul-Islam
Copy link

Can you please explain how it works?

@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