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, 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 pass 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 lodash library that converts 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