{

How to convert camelCase string to/from hyphens javascript


camelCase is a string whose second word’s starting letter is Capital, Example is employeeList. This is a short tutorial on Converting camelCase to/from hyphen in JavaScript.

you can

For example, given a string is employeeList, Output converted to dashes. i.e employee-list. so, we have to split the camel case string into words and replace the second word onwards with a hyphen, and update the first letter to a small case.

You can check my other tutorials on string case conversion.

Convert camelCase to hyphens in JavaScript

Following are multiple ways that can be implemented to do the conversion in JavaScript/typescript.

using regular expression

Regular expressions to split into words and convert the first letter of each word into small cases except the first string.

let str = 'employeeListOne';
console.log(str.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase());

Output:

employee-list-one

param-case npm library

Instead of writing custom logic for this, we can use the param-case npm package to do the conversion. It is a very popular package and the most downloaded utility in NodeJS projects.

You can use it in Angular,React, and Vuejs applications for camel case to hyphen case.

First, Install the package using the npm command.

npm install param-case --save

you can import the paramCase class as follows

In javascript,

const paramCase=require("param-case");

In typescript

import { paramCase } from "param-case";

you can see the passed string to paramCase class as follows

paramCase("emptyString"); //=> "empty-string"
paramCase("twoWords"); //=> "two-words"

Convert Hyphen to camelcase in javascript

For example, given input string is in the dashed string, array-list and output is in camel case. i.e ArrayList.

lodash camelCase method

camelCase is a simple utility method in the lodash library that converts a given dashed or space string converts into camelcase. Syntax:

camelCase(string)

The input parameter is a string output is the string returned in camelCase

var dashString = 'array-list';
result = _.camelCase(dashString); // arrayList
THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.