I know of the jQuery $.trim() function, but what I need is a way to trim whitespace from the END of a string only, and NOT the beginning too.
So
str =" this is a string ";
would become
str =" this is a string";
Any suggestions?
Thanks!
The String. trim() method # You can call the trim() method on your string to remove whitespace from the beginning and end of it. It returns a new string.
The $. trim() function removes all newlines, spaces (including non-breaking spaces), and tabs from the beginning and end of the supplied string.
Use the . rstrip() method to remove whitespace and characters only from the end of a string.
To remove whitespace characters from the beginning or from the end of a string only, you use the trimStart() or trimEnd() method.
You can use a regex:
str = str.replace(/\s*$/,"");
It says replace all whitespace at the end of the string with an empty string.
Breakdown:
\s*
: Any number of spaces$
: The end of the stringMore on regular expressions:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions
For some browsers you can use:
str = str.trimRight();
or
str = str.trimEnd();
If you want total browser coverage, use regex.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/trimEnd
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With