Javascript trim function

I use trim a lot. It’s available in most programming languages. Except for Javascript. I’m not sure why it’s not there, but since we should always try to look at things from a positive perspective, we can be glad that it can easily be added. And not only as a standalone function, but integrated right into the string class.

All we need to do is place this code somewhere in our Javascript file:

String.prototype.trim = function ()
{
return this.replace(/^\s*/, "").replace(/\s*$/, "");
}

This function is one of the fastest implementations of trim. I noticed that there are a lot of them floating around out there in cyberspace, and some of them dreadfully slow. I’m happy to stick to a simple and fast solution.

    Leave a Reply

    *