skip to Main Content

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.

2

Answers


  1. 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"
    Login or Signup to reply.
  2. One could describe a pattern which looks for every word boundary followed by any sequence of non-letter but also non-single-quote characters which gets preceded by a single captured letter (/b[^p{L}']+(p{L})/ug). This matching pattern gets entirely replace by the uppercase variant of the captured letter. One then just needs to go after every remaining non-letter and non-number character (sequence) that each will be entirely removed /[^p{L}p{N}]/ug

    function toCamelCase(value) {
      return String(value)
    
        .trim()
        .toLowerCase()
    
        // see ... [https://regex101.com/r/VQWTVY/1]
        .replace(/b[^p{L}']+(p{L})/ug, (_, char) => char.toUpperCase())
    
        // see ... [https://regex101.com/r/VQWTVY/2]
        .replace(/[^p{L}p{N}]/ug, '');
    }
    
    const result2 = toCamelCase('HEy, world');
    console.log(result2); // 'heyWorld'
    
    const result3 = toCamelCase("Yes, that's my student");
    console.log(result3); // 'yesThatsMyStudent'
    .as-console-wrapper { min-height: 100%!important; top: 0; }
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search