Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to trim() white spaces from a string?

JavaScript doesn't seem to have a native trim() method. How can I trim white spaces at the start and end of a string with JavaScript?

like image 561
MDCore Avatar asked Oct 13 '08 07:10

MDCore


People also ask

How do you trim white spaces in a string?

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.).

How do I remove white spaces from a string in Python?

strip() Python String strip() function will remove leading and trailing whitespaces. If you want to remove only leading or trailing spaces, use lstrip() or rstrip() function instead.

How do you get rid of the whitespace at the end of a string?

String result = str. trim(); The trim() method will remove both leading and trailing whitespace from a string and return the result.

How do you trim a white space in C++?

The trim_left() function removes all the leading white spaces. The trim_right() function removes all the trailing white spaces. The trim() function removes all the leading and trailing white spaces.


2 Answers

The shortest form for jQuery:

string = $.trim(string); 

Link

like image 191
Darryl Hein Avatar answered Oct 17 '22 00:10

Darryl Hein


according to this page the best all-around approach is

return str.replace(/^\s\s*/, '').replace(/\s\s*$/, ''); 

Of course if you are using jQuery , it will provide you with an optimized trim method.

like image 26
Pat Avatar answered Oct 16 '22 22:10

Pat