I had a simple Javascript issue today which (for some reason) took a long time to solve.

Basically, I wanted to trim white space from the beginning and end of a string. The standard answer on the internet is as follows;

selectedtext = selectedtext.replace(/^\s+|\s+$/g, '');

What stopped me (for about an hour, in fact), was that it was failing, and Firebug was giving me the error “.replace is not a function”.

I eventually realized that “.replace” is only a function when the operand is a string; in my case, selectedtext was an object, and therefore I needed to cast it to a string, as follows;

selectedtext = selectedtext.toString().replace(/^\s+|\s+$/g, '');

This then gave me the correct result.

Notes:
1. Yes, creating a little trim function would be neater. But there was no value in this case, as it was a very definite one-off requirement in this system
2. jQuery or Prototype already have trim functions built in. But I didn’t want the added weight of the framework on this page for such a simple requirement.
3. A simple command alert(typeof {variable}) is very useful in these cases. Wish I’d used it earlier!