Kebab case is a naming convention where words are written in lowercase and separated by hyphens (-). In JavaScript, strings written in space-separated, camelCase, or snake_case formats can be converted into kebab case using different approaches.
- Kebab case separates words using hyphens and converts them to lowercase.
- Regular expressions can identify spaces, underscores, and word boundaries in camelCase strings.
- JavaScript loops and libraries such as Lodash can also be used for the conversion.
Approach 1: Using the replace() Method
This approach uses regular expressions with the replace() method to identify word boundaries, spaces, and underscores. The matched separators are replaced with hyphens, and the final string is converted to lowercase.
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: Using the match() Method
The match() method can extract individual words from different string formats. The extracted words are then joined using hyphens and converted to lowercase.
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
Approach 3: Using Lodash _.kebabCase() Method
The Lodash _.kebabCase() method provides a simple way to convert strings from different formats into kebab case. It automatically handles spaces, underscores, hyphens, and uppercase letters.
const _ = require("lodash");
console.log(_.kebabCase("GEEKS__FOR__GEEKS"));
console.log(_.kebabCase("GEEKS-----FOR_____Geeks"));
console.log(_.kebabCase("geeks--FOR--geeks"));
Output
geeks-for-geeks
geeks-for-geeks
geeks-for-geeks
Approach 4: Using a for Loop
This approach iterates through each character in the string. When an uppercase letter is found, a hyphen is added before it when necessary. Spaces, underscores, and existing hyphens are also handled during the conversion.
function toKebabCase(str) {
let result = "";
for (let i = 0; i < str.length; i++) {
const char = str[i];
if (
char.toUpperCase() === char &&
char.toLowerCase() !== char
) {
if (i > 0) {
result += "-";
}
result += char.toLowerCase();
} else if (
char === " " ||
char === "_" ||
char === "-"
) {
result += "-";
} else {
result += char;
}
}
return result;
}
console.log(
toKebabCase("welcomeToGeeksForGeeks")
);
Output
welcome-to-geeks-for-geeks