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
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:
This checks to see if there is a character at the end and if not, it just breaks.
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:
Trimming the leading spaces in the loop:
Array#reduce()
variant: