javascript - Trimming whitespace from the END of a string only, with jQuery - Stack Overflow

I know of the jQuery $.trim() function, but what I need is a way to trim whitespace from the END of a s

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 badges
Add a comment  | 

2 Answers 2

Reset to default 42

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

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1737632283a3959848.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信