How to convert a string into kebab case using JavaScript ?
Last Updated :
21 May, 2024
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: GeeksForGeeks
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:
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. 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'));
Outputgeeks-for-geeks
geeks-for-geeks
geeks-for-geeks
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'));
Outputgeeks-for-geeks
geeks-for-geeks
geeks-for-geeks
Lodash _.kebabCase() method is used to convert the given string into a kebab case string. kebabCase is the practice of writing identifiers using hyphens instead of spaces. The string can be space-separated, dash-separated, or can be separated by underscores.
Syntax:
_.kebabCase([string='']);
Example: In this example, we are using Lodash _.kebabCase() method
JavaScript
const _ = require('lodash');
let str1 = _.kebabCase("GEEKS__FOR__GEEKS");
console.log(str1);
let str2 = _.kebabCase("GEEKS-----FOR_____Geeks");
console.log(str2);
let str3 = _.kebabCase("geeks--FOR--geeks");
console.log(str3);
Output:
"geeks-for-geeks"
"geeks-for-geeks"
"geeks-for-geeks"
Approach 4: Using for loop
In this approach we iterate over each character in the string using for loop. For each character, if it's uppercase and not the first character, add a hyphen before converting it to lowercase. Replace spaces, underscores with hyphens. Append all other characters directly to the new string.
Example: In this example, we are using the above-explained approach.
JavaScript
function toKebabCase(str) {
let kebabCase = '';
for (let i = 0; i < str.length; i++) {
const char = str[i];
if (char.toUpperCase() === char && char.toLowerCase() !== char) {
if (i > 0) {
kebabCase += '-';
}
kebabCase += char.toLowerCase();
} else if (char === ' ' || char === '_' || char === '-') {
kebabCase += '-';
} else {
kebabCase += char;
}
}
return kebabCase;
}
console.log(toKebabCase("welcomeToGeeksForGeeks"));
Outputwelcome-to-geeks-for-geeks
Similar Reads
How to convert a string to snake case using JavaScript ?
In this article, we are given a string in and the task is to write a JavaScript code to convert the given string into a snake case and print the modified string. Examples: Input: GeeksForGeeks Output: geeks_for_geeks Input: CamelCaseToSnakeCase Output: camel_case_to_snake_caseThere are some common a
2 min read
How to Convert String to Camel Case in JavaScript?
We will be given a string and we have to convert it into the camel case. In this case, the first character of the string is converted into lowercase, and other characters after space will be converted into uppercase characters. These camel case strings are used in creating a variable that has meanin
4 min read
How to replace all dots in a string using JavaScript ?
We will replace all dots in a string using JavaScript. There are multiple approaches to manipulating a string in JavaScript. Table of Content Using JavaScript replace() MethodUsing JavaScript Split() and Join() Method Using JavaSccript reduce() Method and spread operatorUsing JavaScript replaceAll()
4 min read
How to convert an object to string using JavaScript ?
To convert an object to string using JavaScript we can use the available methods like string constructor, concatenation operator etc. Let's first create a JavaScript object. JavaScript // Input object let obj_to_str = { name: "GeeksForGeeks", city: "Noida", contact: 2488 }; Examp
4 min read
How to convert Integer array to String array using JavaScript ?
The task is to convert an integer array to a string array in JavaScript. Here are a few of the most used techniques discussed with the help of JavaScript. Approaches to convert Integer array to String array:Table of ContentApproach 1: using JavaScript array.map() and toString() methodsApproach 2: Us
2 min read
Convert string into date using JavaScript
In this article, we will convert a string into a date using JavaScript. A string must follow the pattern so that it can be converted into a date. A string can be converted into a date in JavaScript through the following ways: Table of Content Using JavaScript Date() constructorUsing JavaScript toDat
3 min read
How to Convert String of Objects to Array in JavaScript ?
This article will show you how to convert a string of objects to an array in JavaScript. You have a string representing objects, and you need to convert it into an actual array of objects for further processing. This is a common scenario when dealing with JSON data received from a server or stored i
3 min read
Convert Array to String in JavaScript
In JavaScript, converting an array to a string involves combining its elements into a single text output, often separated by a specified delimiter. This is useful for displaying array contents in a readable format or when storing data as a single string. The process can be customized to use differen
7 min read
Convert a JavaScript Enum to a String
Enums in JavaScript are used to represent a fixed set of named values. In JavaScript, Enumerations or Enums are used to represent a fixed set of named values. However, Enums are not native to JavaScript, so they are usually implemented using objects or frozen arrays. In this article, we are going to
2 min read
JavaScript - Convert a String to Boolean in JS
Here are different ways to convert string to boolean in JavaScript.1. Using JavaScript == OperatorThe == operator compares the equality of two operands. If equal then the condition is true otherwise false. Syntaxconsole.log(YOUR_STRING == 'true');JavaScriptlet str1 = "false"; console.log(str1 == 'tr
3 min read