javascript 仅使用 jQuery 从字符串的末尾修剪空格
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17938186/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Trimming whitespace from the END of a string only, with jQuery
提问by Sharon 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.
我知道 jQuery $.trim() 函数,但我需要的是一种仅从字符串的末尾而不是开头修剪空格的方法。
So
所以
str =" this is a string ";
would become
会成为
str =" this is a string";
Any suggestions?
有什么建议?
Thanks!
谢谢!
回答by go-oleg
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
\s*
: 任意数量的空格$
: 字符串的结尾
More on regular expressions:
更多关于正则表达式:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions
回答by Marco Gaspari
For some browsers you can use:
str = str.trimRight();
or
str = str.trimEnd();
对于某些浏览器,您可以使用:
str = str.trimRight();
或
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://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/trimEnd