JavaScript String – How to Trim a String in JavaScript
javascriptstringtrim
How do I remove all whitespace from the start and end of the string?
Best Answer
All browsers since IE9+ have trim() method for strings.
" \n test \n ".trim(); // returns "test" here
For 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.
Why not just use substring... string.substring(0, 7); The first argument (0) is the starting point. The second argument (7) is the ending point (exclusive). More info here.
var string = "this is a string";
var length = 7;
var trimmedString = string.substring(0, length);
Best Answer
All browsers since IE9+ have
trim()
method for strings.For those browsers who does not support
trim()
, you can use this polyfill from MDN:That said, if using
jQuery
, then$.trim(str)
is always available, which handles undefined/null as well.See this: