Last active
February 2, 2020 05:53
-
-
Save tdukart/b87afb278c41245741ae7a0c355a0a0b to your computer and use it in GitHub Desktop.
JavaScript Kebab Case function
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
/** | |
* 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; | |
} |
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
Add Unicode support.
Can you please explain how it works?
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
Last regex is missing a
+
, so multiple trailing-
will not be caught.