Saturday 4 August 2018

Trim string in JavaScript?

Answer


Answer





How do I trim a string in JavaScript?


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:



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, $.trim(str) is also available and handles undefined/null.







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,' ');};

No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...