This piece of code is offered on the internet. It capitalizes the first letter of every sentence in a string and makes all the others lowercase. The code works as promised, but can be made much more efficient. I'll show you how to reduce the 61 lines of code to 18 or 8 lines of clear unobfuscated code.
Examine the original code both to understand how it works, but also see if you can spot the areas where it can be improved.
You may want to for reference
Accepting that the code yields the desired results, we can focus on the quality.
There are a number of issues that can be address.
Accessing data is quicker when it is local. Failing to declare variables with var makes them public reducing performance and risking conflicts with globals of the same name.
As written the code will only work with one form field: formdemo.convert. In commputer science jargon the function is tightly coupled to data outside the function. This limits code reuse and makes maintenance more difficult.
There is always a cost to a function call (and calls through object property chains). This is particularly true for JavaScript string methods since the primative string has to be converted to an object before the call can be made. It is better to make the charAt call once and store the results locally.
The second argument for substring is optional. When omitted, it includes everything to the end of the string. This is the same as using string.length except the conversion to an object to determine the length isn't needed.
The last two items will work themselves out in the first pass at refactoring.
Some of the notes on efficiency may seem like nit picking. Modern processors are fast and there is lots of RAM. Consequently, demonstration code, even poor code, runs fast. It's when the code runs in a loop or runs on large strings that performance takes a hit.
Compare the original with the First Refactoring.