Home > Software design >  Writing function to convert given name into camelCase
Writing function to convert given name into camelCase

Time:12-25

It works for some name but doesn’t work for lastName that starts with capital letters.

const toCamelCase = function(firstName, lastName) {
  console.log(firstName.toLowerCase()   lastName.toLowerCase().replace(lastName[0], lastName[0].toUpperCase()));
};

toCamelCase('albert', 'einstein');
toCamelCase('MR', 'beast');
toCamelCase('john', 'SMITH');

CodePudding user response:

If you save lastName.toLowerCase() first it will solve your problem.

const toCamelCase = function (firstName, lastName) {
  const convertedLastName = lastName.toLowerCase();
  console.log(
    firstName.toLowerCase()  
      convertedLastName.replace(convertedLastName[0], convertedLastName[0].toUpperCase())
  );
};
toCamelCase('albert', 'einstein'); 
toCamelCase('MR', 'beast');
toCamelCase('john', 'SMITH');

CodePudding user response:

You can also try doing it this way:

export const toCamelCase = (firstName, lastName) => {
    return `${firstName.toLowerCase()}${lastName.charAt(0).toUpperCase()}${lastName.slice(1).toLowerCase()}`;
};
  • Related