How to usethe match() method in Javascript
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.
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('w3wiki'));
console.log(kebabCase('Geeks_For_Geeks'));
Output
geeks-for-geeks geeks-for-geeks geeks-for-geeks
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.
Examples:
Input: Geeks For Geeks
Output: geeks-for-geeks
Input: w3wiki
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:
Table of Content
- Approach 1: Using the replace() method
- Approach 2: Using the match() method
- Approach 3: Using Lodash _.kebabCase() method
- Approach 4: Using for loop
Contact Us