65.9K
CodeProject is changing. Read more.
Home

Create Trim function in javascript

starIconstarIconstarIconstarIconemptyStarIcon

4.00/5 (2 votes)

Nov 2, 2010

CPOL
viewsIcon

21811

You can define a trim function which trims leading and trailing space in JavaScript by using any one of the following ways: way 1:
String.prototype.trim = function() {  return this.replace(/^\s+|\s+$/g, '');  }
way 2:
function trim()
{
 return this.replace(/^\s+|\s+$/g, ''); 
}
The following function shows how to use the trim function
function temp()
{

 var str='    maninder     ';
 alert(str.trim());
}
You will see 'maninder' in the alert box. All the leading and trailing space are trimmed. :)