Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You could assert not ' before matching an optional char a-z

function toCamelCase(input) {
  return input
    .toLowerCase()
    .replace(/\W+((?<!')[a-z])?/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"
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading