Error in accepting the answer, though the result is the required one

For the algorithm challenge Title Case a Sentence I have written the code -

function titleCase(str) {
  var strvar = str.toLowerCase();
  var strsplit1 = strvar.split(" ");
  var str1;
  var str2 = "";
  for(i = 0; i<strsplit1.length; i++){
  str1 = strsplit1[i];
    str1 = str1.replace(str1[0],str1[0].toUpperCase());
    str2 += str1 + " ";
  return str2;

titleCase("I'm a little tea pot");

It gives the required result, but still not moving ahead…

You have an extra space at the end. Fastest fix would be to trim it off your string before returning it, another option would be to overwrite the words in the array and use .join() on it, that way you won’t need to create that many intermediate variables.

1 Like

as @forkerino mentioned that there is extra space at the end.
To solve this add this code after for loop.

str2 = str2.split(' '); str2.pop(); return str2.join(' ');

to remove that extra space first split str2 string to array with space.
x y z => [“x”,“y”,“z”,""]

now just remove last element of array using pop()
[“x”,“y”,“z”,""] => [“x”,“y”,“z”]

join the array with space using join()
[“x”,“y”,“z”] => x y z

1 Like

That seems overly complex. You can just use the .trim() method on str2

1 Like

While it’s not required, you can benefit greatly from the “helpful links” in each of these challenges. They refer you to the built in methods that simplify many of the issues you encounter in the challenge. e.g “Array.prototype.join() joins all elements of an array (or an array-like object) into a string.” Add a separator argument (’ ') and it returns a string with the supplied separator between each element. This means no extra space to deal with at the end of the string.

1 Like

Thanks a lot @forkerino @Marvin9 and @wshill for the inputs and solutions, I removed the space at the end… :grin:

1 Like