最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin24浏览0评论

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

发布评论

评论列表(0)

  1. 暂无评论