OiO.lk Blog javascript How to convert a string into camel case with JavaScript regex without apostrophe and white space?
javascript

How to convert a string into camel case with JavaScript regex without apostrophe and white space?


I am struggling on how to convert a string into camel case without apostrophe and white space. Here is my code so far:

function toCamelCase(input) {
  return input
    .toLowerCase()
    .replace(/['\W]+(.)?/g, (_, char) => (char ? char.toUpperCase() : ""))
    .replace(/^./, (char) => char.toLowerCase());
}

const result2 = toCamelCase("HEy, world");
console.log(result2); // "heyWorld"

const result3 = toCamelCase("Yes, that's my student");
console.log(result3); // "yesThatsMyStudent"

""HEy, world"" works. The problem is that it is failing on "Yes, that’s my student". I got "yesThatSMyStudent" instead of "yesThatsMyStudent". I have no idea why the "s" in "that’s" is not lowercase. Can someone please explain why this is happening and point me in the right direction? Thank you.

Edit: Just for educational purpose, how would you handle a case if a word is quoted? For example, Yes, that's my 'student' should be yesThatsMyStudent.



You need to sign in to view this answers

Exit mobile version