Skip to content
Related Articles
Get the best out of our app
GeeksforGeeks App
Open App
geeksforgeeks
Browser
Continue

Related Articles

How to convert a string into kebab case using JavaScript ?

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

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. 

For examples:

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

Input:   GeeksForGeeks
Output:  geeks-for-geeks

Input:  Geeks_for_geeks
Output: geeks-for-geeks

This can be achieved in the following ways:

Approach 1: By 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. And 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: By 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
My Personal Notes arrow_drop_up
Last Updated : 26 Apr, 2023
Like Article
Save Article
Similar Reads
Related Tutorials