HomeLanguagesJavascriptHow to convert a string into kebab case using JavaScript ?

How to convert a string into kebab case using JavaScript ?

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: neveropen-for-neveropen

Input:   GeeksForGeeks
Output:  neveropen-for-neveropen

Input:  Geeks_for_neveropen
Output: neveropen-for-neveropen

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:

neveropen-for-neveropen
neveropen-for-neveropen
neveropen-for-neveropen

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:

neveropen-for-neveropen
neveropen-for-neveropen
neveropen-for-neveropen
RELATED ARTICLES

Most Popular

Dominic
32704 POSTS0 COMMENTS
Milvus
131 POSTS0 COMMENTS
Nango Kala
7076 POSTS0 COMMENTS
Nicole Veronica
12212 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12303 POSTS0 COMMENTS
Shaida Kate Naidoo
7198 POSTS0 COMMENTS
Ted Musemwa
7457 POSTS0 COMMENTS
Thapelo Manthata
7175 POSTS0 COMMENTS
Umr Jansen
7161 POSTS0 COMMENTS