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

Input:   GeeksForGeeks
Output:  zambiatek-for-zambiatek

Input:  Geeks_for_zambiatek
Output: zambiatek-for-zambiatek

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:

zambiatek-for-zambiatek
zambiatek-for-zambiatek
zambiatek-for-zambiatek

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:

zambiatek-for-zambiatek
zambiatek-for-zambiatek
zambiatek-for-zambiatek

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Check Also
Close
Back to top button