Skip to content
Related Articles

Related Articles

Improve Article

How to convert a string into kebab case using JavaScript ?

  • Last Updated : 01 Apr, 2021

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 by 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 replacing them with a hyphen. And the second replace function is used for getting the spaces and underscores and replacing them with a hyphen. 



Javascript




<script>
    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'));
</script>

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.

Javascript




<script>
    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'));
</script>

Output:

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



My Personal Notes arrow_drop_up
Recommended Articles
Page :