Trimming whitespace from the END of a string only, with jQuery

你离开我真会死。 提交于 2020-12-29 02:55:52

问题


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!


回答1:


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




回答2:


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



来源:https://stackoverflow.com/questions/17938186/trimming-whitespace-from-the-end-of-a-string-only-with-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!