Tag Archives: javascript trim

Useful trim prototype (function) in core javascript

Below is the most commonly used trim prototype/function in javascript. Posting for reference.

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

You can place the above code (wrapped in <script></script>) inside <header> section of your web page or you can place it in an external javascript file which you include in the header section.

//how to use it example
var my_string = "  Hello trim me           ";
var my_string_trimmed = my_string.trim();
//my_string_trimmed now has "Hello trim me"

Very useful tool.