Open In App

How to convert a string into kebab case using JavaScript ?

Improve
Improve
Like Article
Like
Save
Share
Report

Given a string with space-separated or camel case or snake case letters, the task is to find the kebab case of the following string. 

Examples:

Input:  Geeks For Geeks
Output: geeks-for-geeks

Input: GeeksForGeeks
Output: geeks-for-geeks

Input: Geeks_for_geeks
Output: geeks-for-geeks

Below are the approaches used to convert a string into a kebab case using JavaScript:

Approach 1: Using the replace() method

Here we have a function named kebabCase which takes a string and returns a string after converting the kebab case. Here we are using replace method two times because the first replace method is to get all the letters that are near to the uppercase letters and replace them with a hyphen. The second replace function is used for getting the spaces and underscores and replacing them with a hyphen.

Example: In this example, we are using the above-explained approach.

Javascript




const kebabCase = string => string
    .replace(/([a-z])([A-Z])/g, "$1-$2")
    .replace(/[\s_]+/g, '-')
    .toLowerCase();
 
console.log(kebabCase('Geeks For Geeks'));
console.log(kebabCase('GeeksForGeeks'));
console.log(kebabCase('Geeks_For_Geeks'));


Output

geeks-for-geeks
geeks-for-geeks
geeks-for-geeks

Approach 2: Using the match() method

Here, we use the map method that checks for space, capital letters, and underscores. It creates an array and pushes the words that separate the strings. Now join the array with the hyphen using the join(). After that convert the whole string into a lower case.

Example: In this example, we are using the above-explained approach.

Javascript




const kebabCase = str => str
    .match(/[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+/g)
    .join('-')
    .toLowerCase();
 
console.log(kebabCase('Geeks For Geeks'));
console.log(kebabCase('GeeksForGeeks'));
console.log(kebabCase('Geeks_For_Geeks'));


Output

geeks-for-geeks
geeks-for-geeks
geeks-for-geeks

Approach 3: Using Lodash _.kebabCase() method

Lodash _.kebabCase() method is used to convert the given string into a kebab case string. kebabCase is the practice of writing identifiers using hyphens instead of spaces. The string can be space-separated, dash-separated, or can be separated by underscores.

Syntax:

_.kebabCase([string='']);

Example: In this example, we are using Lodash _.kebabCase() method

Javascript




const _ = require('lodash');
 
let str1 = _.kebabCase("GEEKS__FOR__GEEKS");
console.log(str1);
 
let str2 = _.kebabCase("GEEKS-----FOR_____Geeks");
console.log(str2);
 
let str3 = _.kebabCase("geeks--FOR--geeks");
console.log(str3);


Output:

"geeks-for-geeks"
"geeks-for-geeks"
"geeks-for-geeks"


Last Updated : 29 Dec, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads