How do I trim a string in JavaScript? That is, how do I remove all whitespace from the beginning and the end of the string in JavaScript?
Use the Native JavaScript Methods: String.trimLeft(), String.trimRight(), and String.trim().
String.trim()
is supported in IE9+ and all other major browsers:
' Hello '.trim() //-> 'Hello'
String.trimLeft()
and String.trimRight()
are non-standard, but are supported in all major browsers except IE
' Hello '.trimLeft() //-> 'Hello '
' Hello '.trimRight() //-> ' Hello'
IE support is easy with a polyfill however:
if (!''.trimLeft) {
String.prototype.trimLeft = function() {
return this.replace(/^\s+/,'');
};
String.prototype.trimRight = function() {
return this.replace(/\s+$/,'');
};
if (!''.trim) {
String.prototype.trim = function() {
return this.replace(/^\s+|\s+$/g, '');
};
}
}