This is our final pass at refactoring the code. Actually, there are two end results; the first using string methods reduces the original code by 43 lines to 18. The second, uses a regular expression to reduce the original code by 54 lines to just 7.

You may want to for reference

How did all those line get removed? The original code and our first refactoring split out the sentences based on punctuation and then split the words delimited by spaces. But, there was no reason to process the words individually. And, then a trick with split eliminated a bunch more.

The changes to note are:

See the section on Regular Expressions to learn more about the RegExp objects used in split and search above and replace below. The code can be made smaller yet with regular expressions.

You may want to for reference

The replace method can take a regular expression for the string to replace and a function as the replacement. In this regular expression, the cnvrt function is passed a punctuation (except for the first sentence), space and character, since toUpperCase only affects a through z toUpperCase can be used on all three characters and have the desired results.