Trim method in JavaScript

December 28, 2010 by Sandeep Bhardwaj | Tags:


We can use String.replace method to trim a string in javascript.

//method for trim a complete string like "  Hello World   "  
function trim(str) {  
 return str.replace(/^\s+|\s+$/g,"");  
}  

//method for left trim a string like "   Hello World"  
function leftTrim(str) {  
 return str.replace(/^\s+/,"");  
}  

//method for right trim a string like "Hello World   "  
function rightTrim(str) {  
 return str.replace(/\s+$/,"");  
}