patternjavascriptCritical
Trim string in JavaScript
Viewed 0 times
stringjavascripttrim
Problem
How do I remove all whitespace from the start and end of the string?
Solution
All browsers since IE9+ have
For those browsers who does not support
That said, if using
See this:
trim() method for strings." \n test \n ".trim(); // returns "test" hereFor those browsers who does not support
trim(), you can use this polyfill from MDN:if (!String.prototype.trim) {
(function() {
// Make sure we trim BOM and NBSP
var rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g;
String.prototype.trim = function() {
return this.replace(rtrim, '');
};
})();
}
That said, if using
jQuery, then $.trim(str) is always available, which handles undefined/null as well.See this:
String.prototype.trim=function(){return this.replace(/^\s+|\s+$/g, '');};
String.prototype.ltrim=function(){return this.replace(/^\s+/,'');};
String.prototype.rtrim=function(){return this.replace(/\s+$/,'');};
String.prototype.fulltrim=function(){return this.replace(/(?:(?:^|\n)\s+|\s+(?:$|\n))/g,'').replace(/\s+/g,' ');};
Code Snippets
" \n test \n ".trim(); // returns "test" hereContext
Stack Overflow Q#498970, score: 941
Revisions (0)
No revisions yet.