Syntax, Parameter and Return Value
Syntax:
_.kebabCase([string=''])
Parameters:
[string=''] (string): The string to convert.
Return Value:
(string) - Returns the kebab cased string.
Examples
Converting a Regular String to Kebab Case:
JavaScript
var _ = require('lodash');
var text = 'Hello World';
console.log(_.kebabCase(text));

You can also try this code with Online Javascript Compiler
Run Code
Output:
'hello-world'
Demonstrates converting a space-separated string to kebab case.
Creating URL Slugs:
JavaScript
var title = 'Lodash Library: A Comprehensive Overview';
var slug = _.kebabCase(title);
console.log(slug);

You can also try this code with Online Javascript Compiler
Run Code
Output:
'lodash-library-a-comprehensive-overview'
Shows converting a title to a URL-friendly slug in kebab case.
Handling Strings with Punctuation and Spaces:
JavaScript
var phrase = 'JavaScript: The Good Parts!';
console.log(_.kebabCase(phrase));

You can also try this code with Online Javascript Compiler
Run Code
Output:
'java-script-the-good-parts'
An example of kebab casing a string with various punctuation marks and spaces.
Standardizing CSS Class Names:
JavaScript
var className = 'MainContainer Highlighted';
console.log(_.kebabCase(className));

You can also try this code with Online Javascript Compiler
Run Code
Output:
'main-container-highlighted'
Demonstrates converting class names to kebab case for use in CSS.
Frequently Asked Questions
How does _.kebabCase() handle non-alphanumeric characters?
_.kebabCase() removes non-alphanumeric characters and uses hyphens to separate words.
Can _.kebabCase() handle camelCase and snake_case strings?
Yes, _.kebabCase() can convert strings from camelCase, snake_case, and other formats into kebab case.
Is _.kebabCase() suitable for all string conversion needs?
_.kebabCase() is ideal for converting strings to kebab case. For other naming conventions like camel case or snake case, different Lodash methods or custom logic would be required.
Conclusion
Lodash's _.kebabCase() method provides an efficient and straightforward way to convert strings of various formats to kebab case. It's particularly useful for creating URL slugs, standardizing CSS class names, and ensuring text string consistency in web and application development.
You can refer to our guided paths on the Coding Ninjas. You can check our course to learn more about DSA, DBMS, Competitive Programming, Python, Java, JavaScript, etc.
Also, check out some of the Guided Paths on topics such as Data Structure and Algorithms, Competitive Programming, Operating Systems, Computer Networks, DBMS, System Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry Experts.