Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trim string in JavaScript?

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?

like image 767
Vinod Avatar asked Jan 31 '09 15:01

Vinod


People also ask

How do you trim a string in JavaScript?

trim() The trim() method removes whitespace from both ends of a string and returns a new string, without modifying the original string. Whitespace in this context is all the whitespace characters (space, tab, no-break space, etc.) and all the line terminator characters (LF, CR, etc.).

Is there a trim function in JavaScript?

In JavaScript, trim() is a string method that is used to remove whitespace characters from the start and end of a string. Whitespace characters include spaces, tabs, etc. Because the trim() method is a method of the String object, it must be invoked through a particular instance of the String class.

What trim () in string does?

Trim() Removes all leading and trailing white-space characters from the current string.

How do you trim a string at the beginning or ending in JavaScript?

JavaScript provides three functions for performing various types of string trimming. The first, trimLeft() , strips characters from the beginning of the string. The second, trimRight() , removes characters from the end of the string. The final function, trim() , removes characters from both ends.


1 Answers

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, $.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,' ');}; 
like image 160
Pradeep Kumar Mishra Avatar answered Oct 03 '22 05:10

Pradeep Kumar Mishra