Pages

Wednesday, March 14, 2018

Javascript trim

Now a days almost all browsers support trim function. e.g.


 "   Leading and Trailing whitespace    ".trim(); 


will result

"Leading and Trailing whitespace"


If the trim function is not supported you can use replace function with regular expression:


 "   Leading and Trailing whitespace    ".replace(/^\s+|\s+$/g, ''); 


The regular expression modifier `g` is very important to be effectively removing the trailing white spaces.