Computer >> Computer tutorials >  >> Programming >> Javascript

Converting any case to camelCase in JavaScript


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 −

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