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!
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!
Share Improve this question asked Jul 30, 2013 at 4:14 Sharon SSharon S 3652 gold badges3 silver badges10 bronze badges2 Answers
Reset to default 42You 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 string
More 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