Basic Algorithm Scripting: Title Case a Sentence: code is not working

Hi, I wonder why the following code does not work? It logs the proper result:

https://jsfiddle.net/sgLvdac0/

I removed also the last whitespace or added a dot at the end: with no success.

titleCase(“I’m a little tea pot”) should return I’m A Little Tea Pot.
titleCase(“sHoRt AnD sToUt”) should return Short And Stout.
titleCase(“HERE IS MY HANDLE HERE IS MY SPOUT”) should return Here Is My Handle Here Is My Spout.

Thank you for any suggestions!

Without too much time to dig in to your code, this line jumped out at me as obviously incorrect:

output = output += charReplacement + " ";

I suspect you just meant to use a single += there.

Also, what are you getting in your console logs?

I need to separate words by whitespace, that’s why + " " was inserted.

Results:
titleCase(“HERE IS MY HANDLE HERE IS MY SPOUT”) => Here Is My Handle Here Is My Spout
titleCase(“I’m a little tea pot”) => I’m A Little Tea Pot
titleCase(“sHoRt AnD sToUt”) => Short And Stout

I can remove the last whitespace or add a full stop, but with no success.

That looks like the right output, but I suspect you’re adding an additional space to the end. Try returning output.trim(). It’s not at all how I’d do it, but it ought to pass the test well enough.

https://jsfiddle.net/sg1v4fkp/

Removed the last space using regular expression, but still no luck :slight_smile:

If you console.log(output) what do you see in the console?

For titleCase(“sHoRt AnD sToUt”) I can see Short And Stout (suggested output) with no whitespace in the end. But it does not pass the test.
What can I do to get to know, why it is not working?

It works with a trim used. I need to make sure, why?

edited: Ah, I applied it to console log, not return itself!

If trim worked and your regex didn’t, then two things are true:

  1. You were appending space to the output. I can see from your algorithm that this is the case.

  2. Your regex didn’t work because it was used incorrectly. I can’t tell, since I can’t see your regex-using statement.

You could still clean up this code a little more, starting with the += issue I mentioned. Ultimately you can boil it down to a one-liner, either with a relatively fancy regex .replace() or a chain of .split(), .map(), and .join(). (Ultimately most of the “do X for each word” problems can be boiled down to those methods)

1 Like

It works with a regex https://jsfiddle.net/ueadpx5v/
I applied it to a console log, not the return statement by a mistake, so it did not.

Thanks for suggesting a few methods, I will try to rewrite it. I can see my code is not so good (but it works).