How to Convert a String to Kebab Case in JavaScript

08/02/2021

Contents

In this article, you will learn how to convert a string to kebab case in JavaScript.

Converting a string to kebab case in JavaScript

Kebab case is a naming convention where words in a sentence are separated by hyphens. For example, “hello-world” is in kebab case.

Using regular expression and string methods

The first method is using regular expression and string methods to convert a string to kebab case. Here is an example code snippet:

function toKebabCase(str) {
  return str.replace(/([a-z])([A-Z])/g, '$1-$2')
            .replace(/\s+/g, '-')
            .toLowerCase();
}
console.log(toKebabCase("Hello World")); // Output: "hello-world"

Explanation

  • The regular expression /([a-z])([A-Z])/g matches all occurrences of a lowercase letter followed by an uppercase letter.
  • str.replace(/([a-z])([A-Z])/g, ‘$1-$2’) replaces each match with the lowercase letter followed by a hyphen and the uppercase letter.
  • str.replace(/\s+/g, ‘-‘) replaces all whitespace characters with hyphens.
  • str.toLowerCase() converts the entire string to lowercase.

Using array methods

The second method is using array methods to convert a string to kebab case. Here is an example code snippet:

function toKebabCase(str) {
  return str.split(/\s+/).join('-').toLowerCase();
}
console.log(toKebabCase("Hello World")); // Output: "hello-world"

Explanation

  • str.split(/\s+/) splits the string into an array of words based on whitespace characters.
  • .join(‘-‘) joins the array elements with hyphens.
  • .toLowerCase() converts the entire string to lowercase.

Using lodash library

The third method is using the Lodash library to convert a string to kebab case. Here is an example code snippet:

const _ = require('lodash');

function toKebabCase(str) {
  return _.kebabCase(str);
}
console.log(toKebabCase("Hello World")); // Output: "hello-world"

Explanation

  • _.kebabCase(str) converts a string to kebab case using the Lodash library.