Converting any case to camelCase in JavaScript

JavascriptWeb DevelopmentFront End Technology

Problem

We are required to write a JavaScript function that takes in a string, str, which can be any case (normal, snake case, pascal case or any other).

Our function should convert this string into camelCase string.

For example, if the input to the function is −

Input

const str = 'New STRING';

Output

const output = 'newString';

Example

Following is the code −

 Live Demo

const str = 'New STRING';
const toCamelCase = (str = '') => {
   return str
      .replace(/[^a-z0-9]/gi, ' ')
      .toLowerCase()
      .split(' ')
      .map((el, ind) => ind === 0 ? el : el[0].toUpperCase() + el.substring(1, el.length))
      .join('');
};
console.log(toCamelCase(str));

Output

newString
raja
Published on 22-Apr-2021 11:45:08
Advertisements