Hyphen string to camelCase string in JavaScript

JavascriptWeb DevelopmentObject Oriented ProgrammingFront End Technology

Suppose, we have a string that contains words separated by hyphens like this −

const str = 'this-is-an-example';

We are required to write a JavaScript function that takes in one such string and converts it into a camelCase string.

For the above string, the output should be −

const output = 'thisIsAnExample';

The code for this will be −

const str = 'this-is-an-example';
const changeToCamel = str => {
   let newStr = '';
   newStr = str
   .split('-')
   .map((el, ind) => {
      return ind && el.length ? el[0].toUpperCase() + el.substring(1)
      : el;
   })
   .join('');
   return newStr;
};
console.log(changeToCamel(str));

Following is the output on console −

thisIsAnExample
raja
Published on 09-Oct-2020 11:15:39
Advertisements