Web development and Tech news Blog site. WEBISFREE.com

HOME > js

[JavaScript] Convert CamelCase, PascalCase, and SnakeCase to KebabCase using toKebabCase function.

Last Modified : 24 Feb, 2023 / Created : 24 Feb, 2023
View Count

Various cases can be used for naming texts such as variables. In addition to the representative camel case, there are also Pascal case, kebab case, snake case, and so on.

"Let's change all of them to kebab case!"

Suppose you want to change a text to kebab case using JavaScript. Kebab case is a writing convention that separates strings using a -(dash) symbol and is especially preferred when declaring CSS. For example, like this:

AS-IS 'webIsFree'

TO-BE 'web-is-free'

Let's briefly look at how to do this in this case.

# Converting to JavaScript camel case (Kebab-case)

In the following, we will create a function called toKebabCase(). The function takes a string as an argument named text and returns it as kebab case. To implement this, we can list what is needed to change to kebab case as follows:

  • Convert _ (underscore) to - (dash).
  • Convert all capital letters to - (dash).
  • Remove - (dash) from the beginning of the string.
  • Convert all other capital letters to lowercase.

By performing these three steps, we can obtain kebab case. First, the code for the completed function is as follows:
const toKebabCase = (text) => {
  return text
    .replace(/_/g, '-')
    .replace(/([A-Z])/g, '-$1')
    .replace(/^-/, '')

If we look at the code, we can see that steps 1 and 2 are implemented using regular expressions, and step 3 is applied using the built-in toLowerCase() function for strings. Now, let's check if it works well.

We tested it with several strings to check the result:

// Output result

We can confirm that all camel, pascal, and snake cases have been changed to kebab case. Let's briefly look at each regular expression used in the code.

! Checking the regular expressions used

The function uses three regular expressions:
text.replace(/_/g, '-')
text.replace(/([A-Z])/g, '-$1')
text.replace(/^-/, '')

The first one replaces all underscore (_) characters with dash (-), which is required to convert snake_case to kebab-case.
text.replace(/_/g, '-')

The second one replaces all uppercase letters in camelCase with a dash (-), which is needed to convert camelCase to kebab-case.
text.replace(/([A-Z])/g, '-$1')

The third one removes the dash (-) at the beginning of the string, which is not required in kebab-case.
text.replace(/^-/, '')

That's all for the regular expressions used. We have also converted all remaining uppercase letters to lowercase using toLowerCase().

This concludes our discussion on how to convert a string to kebab-case in JavaScript.

Perhaps you're looking for the following text as well?


    Adding the share function for JavaScript web pages. navigator.share()