Convert String to Kebab Case with JavaScript

JavaScriptJavaScriptBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In this lab, we will explore how to convert a given string into kebab case using JavaScript. Kebab case is a common naming convention in programming where words in a string are separated by hyphens. We will use regular expressions and array methods to split the string into words and then combine them using the kebab case format.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL javascript(("`JavaScript`")) -.-> javascript/BasicConceptsGroup(["`Basic Concepts`"]) javascript(("`JavaScript`")) -.-> javascript/AdvancedConceptsGroup(["`Advanced Concepts`"]) javascript/BasicConceptsGroup -.-> javascript/variables("`Variables`") javascript/BasicConceptsGroup -.-> javascript/data_types("`Data Types`") javascript/BasicConceptsGroup -.-> javascript/arith_ops("`Arithmetic Operators`") javascript/BasicConceptsGroup -.-> javascript/comp_ops("`Comparison Operators`") javascript/AdvancedConceptsGroup -.-> javascript/higher_funcs("`Higher-Order Functions`") subgraph Lab Skills javascript/variables -.-> lab-28653{{"`Convert String to Kebab Case with JavaScript`"}} javascript/data_types -.-> lab-28653{{"`Convert String to Kebab Case with JavaScript`"}} javascript/arith_ops -.-> lab-28653{{"`Convert String to Kebab Case with JavaScript`"}} javascript/comp_ops -.-> lab-28653{{"`Convert String to Kebab Case with JavaScript`"}} javascript/higher_funcs -.-> lab-28653{{"`Convert String to Kebab Case with JavaScript`"}} end

Converting a string to kebab case

To convert a string to kebab case, follow these steps:

  1. Open the Terminal/SSH and type node to start practicing coding.
  2. Use String.prototype.match() to break the string into words using an appropriate regular expression.
  3. Use Array.prototype.map(), Array.prototype.join(), and String.prototype.toLowerCase() to combine the words, adding - as a separator.

Here is an example function that performs the conversion:

const toKebabCase = (str) =>
  str &&
  str
    .match(/[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+/g)
    .map((x) => x.toLowerCase())
    .join("-");

You can use this function to convert strings to kebab case as shown below:

toKebabCase("camelCase"); // 'camel-case'
toKebabCase("some text"); // 'some-text'
toKebabCase("some-mixed_string With spaces_underscores-and-hyphens");
// 'some-mixed-string-with-spaces-underscores-and-hyphens'
toKebabCase("AllThe-small Things"); // 'all-the-small-things'
toKebabCase("IAmEditingSomeXMLAndHTML");
// 'i-am-editing-some-xml-and-html'

Summary

Congratulations! You have completed the Kebabcase String lab. You can practice more labs in LabEx to improve your skills.

Other JavaScript Tutorials you may like