skip to Main Content

I’m struggling with this exercise:

Given is a string n. The task is to return the sentence in CamelCase notation. This means that each new word is capitalized and immediately appended to the old word. Start with a lowercase letter.

I’ve tried this:

function camelCase(s) {
  let result = "";

  // Convert the first character to lowercase
  result += s[0].toLowerCase();

  for (let i = 1; i < s.length; i++) {
    // Check for spaces and capitalize the next character
    if (s[i] === ' ') {
      result += s[i + 1].toUpperCase();
      i++; // Skip the space character
    } else {
      result += s[i];
    }
  }

  return result;
}

but get this error: https://phpout.com/wp-content/uploads/2024/04/duZVr.png

2

Answers


  1. You can see from the comments that any string that ends with an empty character will cause the crash.

    Example: "Hi " will crash your code because there is no character after " " to convert to an upper case. The easiest way to handle this is with a simple condition before the crashing line ie:

    ...
    if (s[i] === ' '){
      if (!s[i + 1]) break; // Break since we are at the end of the sentence
      result += s[i + 1].toUpperCase();
    ...
    

    This checks to see if there is a character at the end and if not, it just breaks.

    Login or Signup to reply.
  2. You should check whether the next character exists, as mentioned in another answer: if (!s[i + 1]) break;.
    But you could probably simplify the code checking the previous character instead.

    Also your comment i++; // Skip the space character – we skip the next character already added to the result instead.

    Also you might want to trim the input string, since leading spaces will result in a wrong output:

    function camelCase(s) {
      let result = "";
      s = s.trim();
      result += s[0].toLowerCase();
      for (let i = 1; i < s.length; i++) {
        if(s[i] !== ' ') result += s[i-1] === ' ' ? s[i].toUpperCase() : s[i];
      }
    
      return result;
    }
    
    console.log(JSON.stringify(camelCase(' Hello world ! ')))

    Trimming the leading spaces in the loop:

    function camelCase(s) {
      let result = "";
      for (let i = 0; i < s.length; i++) {
        if(s[i] !== ' ') 
          if(result.length) 
            result += s[i-1] === ' ' ? s[i].toUpperCase() : s[i];
          else result += s[i].toLowerCase();
      }
    
      return result;
    }
    
    console.log(JSON.stringify(camelCase(' Hello world ! ')))

    Array#reduce() variant:

    const camelCase = s => [...s.trim()].reduce((r, c, i, arr) => 
      (i ? c === ' ' || (r += arr[i - 1] === ' ' ? c.toUpperCase() : c) : r += c.toLowerCase(), r), '');
    
    console.log(JSON.stringify(camelCase(' Hello world ! ')))
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search